How to implement linux remote login and sftp through Python

王林
Release: 2023-05-11 17:55:19
forward
1800 people have browsed it
1. Use the shell command
$ sshpass -p ${passwd} ssh -p ${port} -l ${user} -o StrictHostKeyChecking=no xx.xx.xx.xx "ls -l"
Copy after login

Then you will find that your output contains a lot of information that you do not need, but cannot be removed.
For shell commands, you can directly use pipes or redirect standard output to a file to obtain execution results.

2. Use subprocess

Through Python, you can think of using some command execution libraries such as os.popen, os.system, commands, subprocess, etc. to indirectly obtain system information. The output obtained by these libraries not only contains standard output, but also contains standard error information. Therefore, the output must be cleaned and formatted every time to get the data we want.

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) 
# 数据清理
Copy after login

In short, there are several problems with using ssh commands indirectly:

  • Need to install additional sshpass (if password is not required)

  • Too much interference information, data cleaning and formatting are quite troublesome

  • The code implementation is not elegant enough and the readability is too poor

  • ssh connection It cannot be reused. A command can only be executed once per connection.

  • The code cannot be used on all platforms and can only be used on Linux and OSX

##3. Use Paramiko
  • Installation

python3 -m pip install
Copy after login
  • Method 1: Log in via sshclient based on username and password

    This method Unable to reuse ssh connection.

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()
Copy after login
  • Method 2: Transport mode login based on user name and password


    This method can reuse the connection.

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()
Copy after login
  • Method 3: SSHClient login based on public key

    This method cannot reuse the ssh connection.

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()
Copy after login
  • Method 4: Transport mode login based on public key


    This method can reuse the connection.

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()
Copy after login
  • sftp file transfer

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()
Copy after login

The above is the detailed content of How to implement linux remote login and sftp through Python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template