paramiko是基于python实现的SSH用于连接远程服务器并执行相关操作
1 、以用户名和密码的 sshclient 方式登录
def ls_home():
# 建立一个sshclient对象
ssh = paramiko.SSHClient()
# 允许将信任的主机自动加入到host_allow 列表,此方法必须放在connect方法的前面
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 调用connect方法连接服务器
ssh.connect(hostname='192.168.1.103', port=22, username='python', password='123465')
# 执行命令
stdin, stdout, stderr = ssh.exec_command('ls ~')
# 结果放到stdout中,如果有错误将放到stderr中
print(stdout.read().decode())
# 关闭连接
ssh.close()
2 基于用户名和密码的 transport 方式登录
def trans():
# 实例化一个transport对象
trans = paramiko.Transport(('192.168.1.103', 22))
# 建立连接
trans.connect(username='python', password='123465')
# 将sshclient的对象的transport指定为以上的trans
ssh = paramiko.SSHClient()
ssh._transport = trans
# 执行命令,和传统方法一样
stdin, stdout, stderr = ssh.exec_command('ls -l')
print(stdout.read())
# 关闭连接
trans.close()
3 文件传输
def fn_sftp():
# 实例化一个trans对象# 实例化一个transport对象
trans = paramiko.Transport(('192.168.1.103', 22))
# 建立连接
trans.connect(username='python', password='123465')
# 实例化一个 sftp对象,指定连接的通道
sftp = paramiko.SFTPClient.from_transport(trans)
# 发送文件
sftp.put(localpath='/tmp/a.txt', remotepath='/home/python/a.txt')
# 下载文件
# sftp.get(remotepath, localpath)
trans.close()