先安装Python。支持版本Python 2.6,2.7,3.3+。另外Paramiko还依赖Cryptography library。
然后安装paramiko:
pip install paramiko
主要功能:
1 执行命令
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
r=ssh.connect("10.99.206.27",22,"wcadmin", "<password>")
stdin, stdout, stderr = ssh.exec_command("export")
lines=stdout.readlines()
print type(lines)
for line in lines:
print line
ssh.close()
print '-'*20
2 下载文件
t=paramiko.Transport(('10.99.206.27',22))
t.connect(username='wcadmin',password='<password>')
sftp=paramiko.SFTPClient.from_transport(t)
remote_path='/home/wcadmin/test.txt'
local_path="D:\\temp\\tmp\\jumpserver_page\\test.txt"
sftp.get(remote_path,local_path)
t.close()
3 上传文件
t=paramiko.Transport(('10.99.206.27',22))
t.connect(username='wcadmin',password='<password>')
sftp=paramiko.SFTPClient.from_transport(t)
remote_path='/home/wcadmin/test.txt'
local_path="D:\\temp\\tmp\\jumpserver_page\\test.txt"
sftp.put(local_path,remote_path)
t.close()
上传下载默认将会覆盖同名文件。
4 命令行方式与远程服务器交互(基于windows平台)
#-*-coding:UTF-8-*-
import sys
import paramiko
import threading
def read_chan(chan):
while True:
data=chan.recv(256)
if not data:
sys.stdout.write('\r\n*** EOF ***\r\n\r\n')
sys.stdout.flush()
break
sys.stdout.write(data)
sys.stdout.flush()
pass
if __name__=='__main__':
print 'interactive shell command'+'-'*20
client=None
chan=None
try:
client=paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('10.99.206.27',22,'wcadmin','<password>')
chan=client.invoke_shell()
threading.Thread(target=read_chan,args=(chan,)).start()
while True:
d=sys.stdin.read(1)
if not d:
break
chan.send(d)
except paramiko.ssh_exception.AuthenticationException,e:
print('Exception ---> '+str(e))
except SSHException,sshe:
print("SSHException ---> "+str(sshe))
except BaseException,be:
print("Other Exception ---> "+str(be))
finally:
if chan:
chan.close()
if client:
client.close()
print 'end of test'+'*'*20