paramiko是python中一个遵循ssh2协议,并支持以加密和认证的方式 进行远程服务连接的模块

使用方法如下:


使用账号密码链接服务器

import paramiko
#创建对象
ssh = paramiko.SSHClient()
#设置访问策略,默认拒绝所有不明的server,这里使用AutoAddPolicy()添加服务器到 L{HostKeys}对象,允许链接不在know_host文件中的主机,
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
#链接服务器
ssh.connect(hostname="127.0.0.1",port=22,username="will",password="123123")
#远程执行命令,执行结果会返回给stdin.stdout.stderr 三个变量
stdin,stdout,stderr = ssh.exec_command("ls /")
# 读取变量值 并赋值给变量result
result = stdin.read()
#关闭链接
ssh.close()


使用密钥链接服务器

import paramiko
#指定密钥文件
privateKey = paramiko.RSAKey._from_private_key_file("/home/will/id_rsa")
#创建对象
ssh = paramiko.SSHClient()
#设置访问策略,默认拒绝所有不明的server,这里使用AutoAddPolicy()添加服务器到 L{HostKeys}对象,允许链接不在know_host文件中的主机,
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
#链接服务器
ssh.connect(hostname="127.0.0.1",port=22,username="will",pkey=privateKey)
#远程执行命令,执行结果会返回给stdin.stdout.stderr 三个变量
stdin,stdout,stderr = ssh.exec_command("ls /")
# 读取变量值 并赋值给变量result
print stdin.read()
#关闭链接
ssh.close()


两种方法类似,不同的是使用密钥链接服务器的时候需要先指定密钥文件,链接的时候使用执行的密钥文件.


查看SSHClient 类 ,可以发现该类内部封装的其实是 Transport 类

这样的话,我们就可以把上面的代码进行修改

使用账号密码链接服务器

import paramiko
hostInfo = ("127.0.0.1",22)
trans =paramiko.Transport(hostInfo)
trans.connect(username="will",password="123123")
ssh = paramiko.SSHClient()
ssh._transport = trans
stdin,stdout,stderr = ssh.exec_command("ls /")
print stdin.read()
trans.close()

使用密钥链接服务器

import paramiko
privateKey = paramiko.RSAKey._from_private_key_file("/home/will/id_rsa")
hostInfo = ("127.0.0.1",22)
trans =paramiko.Transport(hostInfo)
trans.connect(username="will",pkey=privateKey)
ssh = paramiko.SSHClient()
ssh._transport = trans
stdin,stdout,stderr = ssh.exec_command("ls /")
print stdin.read()
trans.close()


paramiko中的SFTP

基于用户名密码上传下载

import paramiko
 
transport = paramiko.Transport(('127.0.0.1',22))
transport.connect(username='will',password='1')
 
sftp = paramiko.SFTPClient.from_transport(transport)
# 上传/tmp/localFile.py文件至服务器 /tmp/RemoteFile.py
sftp.put('/tmp/localFile.py', '/tmp/RemoteFile.py')
# 将RemoteFile.py 下载到本地 RemoteFile.py
sftp.get('RemoteFile.py', 'RemoteFile.py')
 
transport.close()

基于公钥密钥上传下载

import paramiko
 
private_key = paramiko.RSAKey.from_private_key_file('/home/will/id_rsa')
 
transport = paramiko.Transport(('127.0.0.1', 22))
transport.connect(username='wupeiqi', pkey=private_key )
 
sftp = paramiko.SFTPClient.from_transport(transport)
# 上传/tmp/localFile.py文件至服务器 /tmp/RemoteFile.py
ftp.put('/tmp/localFile.py', '/tmp/RemoteFile.py')
# 将RemoteFile.py下载到本地 RemoteFile.py
sftp.get('RemoteFile.py', 'RemoteFile.py')
 
transport.close()




参考

http://www.cnblogs.com/wupeiqi/articles/5095821.html