python 3 paramiko模块
paramiko是一个用于做远程控制的模块,使用该模块可以对远程服务器进行命令或文件操作,值得一说的是,fabric和ansible内部的远程管理就是使用的paramiko来现实。
在python3中安装
pip3 install paramiko
pycrypto,由于 paramiko 模块内部依赖pycrypto,所以先下载安装pycrypto #在python2中pip3 install pycryptopip3 install paramiko注:如果在安装pycrypto2.0.1时发生如下错误 command 'gcc' failed with exit status 1...可能是缺少python-dev安装包导致如果gcc没有安装,请事先安装gcc
SSHClient
用于连接远程服务器并执行基本命令:
import paramiko# 创建SSH对象ssh = paramiko.SSHClient()# 允许连接不在know_hosts文件中的主机ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())# 连接服务器ssh.connect(hostname='10.100.12.251', port=22, username='root', password='123456')# 执行命令stdin, stdout, stderr = ssh.exec_command('df')# 获取命令结果result = stdout.read()print(result.decode('utf-8'))# 关闭连接ssh.close()
import paramikoprivate_key = paramiko.RSAKey.from_private_key_file('/tmp/id_rsa')transport = paramiko.Transport(('10.100.12.251', 22))transport.connect(username='root', pkey=private_key)ssh = paramiko.SSHClient()ssh._transport = transportstdin, stdout, stderr = ssh.exec_command('df')result=stdout.read()print(result.decode('utf-8')) transport.close()
import paramikofrom io import StringIOkey_str = """-----BEGIN RSA PRIVATE KEY-----xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-----END RSA PRIVATE KEY-----"""private_key = paramiko.RSAKey(file_obj=StringIO(key_str))transport = paramiko.Transport(('10.100.12.251', 22))transport.connect(username='root', pkey=private_key)ssh = paramiko.SSHClient()ssh._transport = transportstdin, stdout, stderr = ssh.exec_command('df')result = stdout.read()print(result.decode('utf-8'))transport.close()print(result)
SFTPClient
用于连接远程服务器并执行上传下载
import paramiko transport = paramiko.Transport(('10.100.12.251',22))transport.connect(username='root',password='123456')sftp = paramiko.SFTPClient.from_transport(transport)# 将location.py 上传至服务器 /tmp/test.pysftp.put('/tmp/id_rsa', '/etc/test.rsa')# 将remove_path 下载到本地 local_pathsftp.get('remove_path', 'local_path') transport.close()
import paramiko transport = paramiko.Transport(('10.100.12.251',22))transport.connect(username='root',password='xxx') sftp = paramiko.SFTPClient.from_transport(transport)# 将location.py 上传至服务器 /tmp/test.pysftp.put('/tmp/id_rsa', '/etc/test.rsa')# 将remove_path 下载到本地 local_pathsftp.get('remove_path', 'local_path') transport.close()