1、远程连接执行命令并返回
#远程登录一台机器用于执行命令import paramiko#创建ssh对象ssh = paramiko.SSHClient()#之前没有建立连接就加入RSA认证ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())ssh.connect(hostname='localhost',port=22,username='qu',password='abcdef')stdin,stdout,stderr = ssh.exec_command('df')out,err = stdout.read(),stderr.read()result = out if out else errprint(result)ssh.close()
2、简单的sftp功能
import paramikotransport = paramiko.Transport(('hostname',22))transport.connect(username='qu',password='abcdef')sftp = paramiko.SFTPClient.from_transport(transport)sftp.put('/tmp/local.py','/tmp/remote.py')sftp.get('/tmp/remote.py','/tmp/local.py')transport.close()
3、基于公钥登录
import paramikoprivate_key = paramiko.RSAKey.from_private_key_file('服务器公钥文件')ssh = paramiko.SSHClient()ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())ssh.connect(hostname='localhost',port=22,username='qu',pkey=private_key)stdin,stdout,stderr = ssh.exec_command('df')result = stdout if stdout else errprint(result)