这篇文章主要讲解了“怎么通过Python实现linux远程登陆及sftp”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“怎么通过Python实现linux远程登陆及sftp”吧!
1. 使用shell命令
$ sshpass -p ${passwd} ssh -p ${port} -l ${user} -o StrictHostKeyChecking=no xx.xx.xx.xx "ls -l"
然后你会发现,你的输出有很多你并不需要,但是又不去不掉的一些信息。
对于shell 命令,可以直接使用管道,或者将标准输出重定向到文件的方法取得执行结果。
2. 使用 subprocess
通过Python可以想到使用 os.popen,os.system,commands,subprocess 等一些命令执行库来间接获取系统信息 。这些库获取的 output 不仅有标准输出,还包含标准错误信息。所以每次都要对 output 进行数据清理,然后整理格式化,才能得到我们想要的数据。
import subprocess
ssh_cmd = "sshpass -p ${passwd} ssh -p 22 -l root -o StrictHostKeyChecking=no xx.xx.xx.xx 'ls -l'"
status, output = subprocess.getstatusoutput(ssh_cmd)
# 数据清理
总之,间接使用ssh命令的几个问题:
3. 使用Paramiko
python3 -m pip install
import paramiko
ssh = paramiko.SSHClient()
# 允许连接不在know_hosts文件中的主机
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 建立连接
ssh.connect("xx.xx.xx.xx", username="root", port=22, password="you_password")
# 使用这个连接执行命令
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command("ls -l")
# 获取输出
print(ssh_stdout.read())
# 关闭连接
ssh.close()
import paramiko
# 建立连接
trans = paramiko.Transport(("xx.xx.xx.xx", 22))
trans.connect(username="root", password="you_passwd")
ssh = paramiko.SSHClient()
ssh._transport = trans
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command("ls -l")
print(ssh_stdout.read())
# 关闭连接
trans.close()
import paramiko
# 指定本地的RSA私钥文件
# 如果建立密钥对时设置了密码,password为passphrase。如果没有passphrase则无需指定password参数。
pkey = paramiko.RSAKey.from_private_key_file('/home/you_username/.ssh/id_rsa', password='12345')
# 建立连接
ssh = paramiko.SSHClient()
ssh.connect(hostname='xx.xx.xx.xx',
port=22,
username='you_username',
pkey=pkey)
# 执行命令
stdin, stdout, stderr = ssh.exec_command('ls -l')
# 结果放到stdout中,如果有错误将放到stderr中
print(stdout.read())
# 关闭连接
ssh.close()
import paramiko
# 指定本地的RSA私钥文件
# 如果建立密钥对时设置了密码,password为passphrase。如果没有passphrase则无需指定password参数。
pkey = paramiko.RSAKey.from_private_key_file('/home/you_username/.ssh/id_rsa', password='12345')
# 建立连接
trans = paramiko.Transport(('xx.xx.xx.xx', 22))
trans.connect(username='you_username', pkey=pkey)
ssh = paramiko.SSHClient()
ssh._transport = trans
# 执行命令,和传统方法一样
stdin, stdout, stderr = ssh.exec_command('df -hl')
print(stdout.read().decode())
# 关闭连接
trans.close()
import paramiko
trans = paramiko.Transport(('xx.xx.xx.xx', 22))
# 建立连接
trans.connect(username='you_username', password='you_passwd')
# 实例化一个 sftp对象,指定连接的通道
sftp = paramiko.SFTPClient.from_transport(trans)
# 发送文件
sftp.put(localpath='/tmp/11.txt', remotepath='/tmp/22.txt')
# 下载文件
sftp.get(remotepath='/tmp/22.txt', localpath='/tmp/33.txt')
trans.close()
感谢各位的阅读,以上就是“怎么通过Python实现linux远程登陆及sftp”的内容了,经过本文的学习后,相信大家对怎么通过Python实现linux远程登陆及sftp这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是天达云,小编将为大家推送更多相关知识点的文章,欢迎关注!