paramiko包含两个核心组件:SSHClient和SFTPClient。
- SSHClient的作用类似于Linux的ssh命令,是对SSH会话的封装,该类封装了传输(Transport),通道(Channel)及SFTPClient建立的方法(open_sftp),通常用于执行远程命令。
- SFTPClient的作用类似与Linux的sftp命令,是对SFTP客户端的封装,用以实现远程文件操作,如文件上传、下载、修改文件权限等操作。
SSH
1 import paramiko 2 ssh = paramiko.SSHClient() 3 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 跳过known_hosts验证(yes/no) 4 ssh.connect(hostname='192.168.0.107',port=22,username='root',password='11111!') # 远程登录 5 stdin,stdout,stderr = ssh.exec_command('df') # 执行命令 6 res,err = stdout.read(),stderr.read() # 接收命令结果 7 result = res if res else err 8 ssh.close() 9 print(result.decode())
SFTP
1 import paramiko 2 transport = paramiko.Transport(('192.168.0.107',22)) 3 transport.connect(username="root",password='11111!') 4 sftp = paramiko.SFTPClient.from_transport(transport) 5 sftp.put('F:/Python-workspaces/week8/day04/ftp_client/client.py','/opt/client.py') # 传文件到服务器的指定目录 6 sftp.get('/opt/isclick.py','C:/Users/Administrator/Desktop/isclick.py') # 将服务器指令目录里的文件传到本地 7 transport.close()
免密方式:SSH
1 import paramiko 2 privite_key = paramiko.RSAKey.from_private_key_file('id_rsa_2048') 3 ssh = paramiko.SSHClient() 4 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy) 5 ssh.connect(hostname='192.168.0.107',port=22,username='root',pkey=privite_key) 6 stdin,stdout,stderr = ssh.exec_command('df') 7 res1 = stdout.read() 8 err = stderr.read() 9 result = res1 if res1 else err 10 print(result.decode())
免密方式:SFTP
1 import paramiko # 导入模块 2 privite_key = paramiko.RSAKey.from_private_key_file('id_rsa_2048') # 定义公钥,指定公钥文件 3 transport = paramiko.Transport(('192.168.0.107',22)) # 实例化transport 4 transport.connect(username='root',pkey=privite_key) # 使用key连接 5 sftp = paramiko.SFTPClient.from_transport(transport) 6 sftp.get('/opt/abc.py', 'qwe.py') 7 sftp.put('id_rsa_2048', '/opt/id_rsa_2048') 8 sftp.close()