ssh远程连接linux服务器并执⾏命令详细⽅法:
SSHClient中的⽅法参数和参数说明
connect(实现ssh连接和校验)hostname:⽬标主机地址
port:主机端⼝
username:校验的⽤户名
password:登录密码
pkey:私钥⽅式⾝份验证
key_filename:⽤于私钥⾝份验证的⽂件名
timeout:连接超时设置
allow_agent:这是布尔型,设置False的时候禁⽌使⽤ssh代理look_for_keys:也是布尔型,禁⽌在.ssh下⾯私钥⽂件compress:设置压缩
exec_command(远程执⾏命令)stdin,stdout,stderr:这三个分别是标准输⼊、输出、错误,⽤来获取命令执⾏结果,并不算⽅法的参数
command:执⾏命令的字符串,带双引号。
bufsize:⽂件缓冲⼤⼩,默认为1
load_system_host_keys(加载本地的
公钥⽂件)
filename:指定远程主机的公钥记录⽂件
set_missing_host_key_policy(远程主机没有密钥)AutoAddPolicy:⾃动添加主机名和主机密钥到本地的HostKeys对象RejectPolicy:⾃动拒绝未知的主机名和密钥(默认)WarningPolicy:接受未知主机,但是会有警告
paramiko的核⼼组件SFTPClient类实现远程⽂件的操作,⽐如上传、下载、权限、状态等。SFTPClient类的⽅法参数和参数说明
from_transport(使⽤⼀个已经通过已经连通的SFTP客户端通道)localpath:本地⽂件的路径
remotepath:远程路径
callback:获取已接收的字节数和总传输的字节数confirm:⽂件上传完毕后是否调⽤stat()⽅法,确定⽂件⼤⼩
get(从SFTP服务器上下载⽂件到本地) remotepath:需下载的⽂件路径localpath:保存本地的⽂件路径callback:和put的⼀样
os⽅法mkdir:简历⽬录
remove:删除
rename:重命名
stat:获取远程⽂件信息listdir:获取指定⽬录列表
shell通道连接:invoke_shell的⽤法
invoke_shell(*args, **kwds)
Request an interactive shell session on this channel. If the server allows it, the channel will then be dir
ectly connected to the stdin, stdout, and stderr of the shell.
Normally you would call get_pty before this, in which case the shell will operate through the pty, and the channel will be connected to the stdin and stdout of the pty.
When the shell exits, the channel will be closed and can’t be reused. You must open a new channel if you wish to open another shell.
在这个通道请求⼀个交互式的shell会话,如果服务允许,这个通道将会直接连接标准输⼊、标准输⼊和错误的shell,通常我们会在使⽤它之前调⽤get_pty的⽤法,这样shell会话是通过伪终端处理的,并且会话连接标准输⼊和输出,当我们shell退出的时候,这个通道也会关闭,并且能再次使⽤,你必修重新开另⼀个shell。
Python 使⽤paramiko.Transport SSH⽅式登录路由器执⾏命令import paramiko
连接linux服务器
import paramiko
ip = "192.168.55.55"
port = 22
username = 'root'
password = '23561314'
# 创建SSH对象
ssh = paramiko.SSHClient()
# 允许连接不在known_hosts⽂件上的主机
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接服务器
# 执⾏命令
print (u'连接%s成功' % ip)
stdin, stdout, stderr = _command('pwd;df')
# # 获取结果
result = ad()
# # 获取错误提⽰(stdout、stderr只会输出其中⼀个)
# err = ad()
# # 关闭连接
# ssh.close()
print(result)
# print(stdin, result, err)
SFTPClient上传下载:
基于⽤户名密码上传下载:
import paramiko
transport = paramiko.Transport(('hostname',22))
sftp = paramiko.SFTPClient.from_transport(transport)
# 将location.py 上传⾄服务器 /tmp/test.py
sftp.put('/tmp/location.py', '/tmp/test.py')
# 将remove_path 下载到本地 local_path
<('remove_path', 'local_path')
transport.close()
基于公钥密钥上传下载:
import paramiko
private_key = paramiko.RSAKey.from_private_key_file('/home/auto/.ssh/id_rsa') transport = paramiko.Transport(('hostname', 22))
sftp = paramiko.SFTPClient.from_transport(transport)
# 将location.py 上传⾄服务器 /tmp/test.py
sftp.put('/tmp/location.py', '/tmp/test.py')
# 将remove_path 下载到本地 local_path
<('remove_path', 'local_path')
transport.close()
封装上传下载代码:
#coding:utf-8
import paramiko
import uuid
class SSHConnection(object):
def __init__(self, host='192.168.2.103', port=22, username='root',pwd='123456'): self.host = host
self.port = port
self.username = username
self.pwd = pwd
self.__k = None
def connect(self):
transport = paramiko.Transport((self.host,self.port))
self.__transport = transport
def close(self):
self.__transport.close()
def upload(self,local_path,target_path):
# 连接,上传
# file_name = ate_file()
sftp = paramiko.SFTPClient.from_transport(self.__transport)
# 将location.py 上传⾄服务器 /tmp/test.py
sftp.put(local_path, target_path)
def download(self,remote_path,local_path):
sftp = paramiko.SFTPClient.from_transport(self.__transport)
ssh命令指定端口<(remote_path,local_path)
def cmd(self, command):
ssh = paramiko.SSHClient()
ssh._transport = self.__transport
# 执⾏命令
stdin, stdout, stderr = _command(command)
# 获取命令结果
result = ad()
print (str(result,encoding='utf-8'))
return result
ssh = SSHConnection()
ssh.upload('s1.py','/tmp/ks77.py')
ssh.download('/tmp/test.py','kkkk',)
ssh.close()
#!/usr/bin/env python
#encoding:utf8
import paramiko
hostname = '192.168.0.202'
port = 22
username = 'root'
password = 'password'
localpath = "D:\Develop\Python\paramiko/\\"  #需要上传的⽂件(源) remotepath = "/data/tmp/"      #远程路径(⽬标)
try:
# 创建⼀个已经连通的SFTP客户端通道
t = paramiko.Transport((hostname, port))
sftp = paramiko.SFTPClient.from_transport(t)
# 上传本地⽂件到规程SFTP服务端
sftp.put(localpath,remotepath) #上传⽂件
# 下载⽂件
<(remotepath,'D:\Develop\Python\paramiko/\\')
# 创建⽬录
# sftp.mkdir('/data/tmp/userdir', 0755)
# 删除⽬录
# dir('/data/tmp/userdir')
# ⽂件重命名
#ame(remotepath,'/data/tmp/')
# 打印⽂件信息
print sftp.stat(remotepath)
# 打印⽬录信息
print sftp.listdir('/data/tmp/')
# 关闭连接
t.close()
except Exception, e:
print str(e)