[python] Operate remote server based on paramiko library

SSH (Secure Shell) is a network security protocol that enables two computers to communicate and share data securely. Currently, the SSH protocol has been widely used all over the world, and most devices support the SSH function. For further explanation of SSH see: Understanding SSH in depth . As a protocol, SSH has many implementations, both commercial and open source. OpenSSH is a popular open-source implementation of the SSH protocol that provides a server-side daemon and client-side tools to encrypt data during remote control and file transfers. OpenSSH server programs are generally not used by developers. OpenSSH provides the following tools:

  • Remote operation via ssh, scp and sftp
  • Key management via ssh-add, ssh-keysign, ssh-keyscan and ssh-keygen
  • The server consists of sshd, sftp-server and ssh-agent

Paramiko is a Python implementation of the SSHv2 protocol. We can directly use the SSH protocol to perform operations on remote servers in Python code, instead of operating remote servers through ssh commands like OpenSSH. See Paramiko official warehouse: paramiko . Paramiko supports Python2.7 or Python3.7 and above. The installation command is as follows:

pip install paramiko

1 Paramiko use

1.1 Introduction to Paramiko

Paramiko provides the core components to implement the SSHv2 server and client. This article mainly introduces the use of the Paramiko client connection code under Linux. The Paramiko client code includes two core classes:

  • SSHClient implements the functions contained in the ssh command in OpenSSH, and is used to connect to the server remotely.
  • SFTPClient implements the functions included in the sftp command in OpenSSH for remote file manipulation.

Paramiko does not provide related functions of the scp command. The functions of scp and sftp are similar, and they are both used for remote operation of files. The difference is that scp is lightweight, and the transfer speed of scp is usually faster than sftp, but sftp provides the function of resuming upload from breakpoints. For a detailed comparison between scp and sftp, see: SCP or SFTP .

1.2 Use of SSHClient

1.2.1 Interface Introduction

SSHClient provides the following common methods:

# 连接远程服务器
def connect(
    self,
    hostname, # 远程服务器地址,必须
    port=22, # 远程服务器端口
    username=None, # 用户名
    password=None, # 密码
    pkey=None, # 用于身份验证的私钥
    key_filename=None, # 私钥文件
    timeout=None, # 超时时间/s
)
# 加载主机密钥
def load_system_host_keys(self, filename=None)
# 在远程服务器上执行命令
# 返回标准输入stdin,标准输出stdout和标准错误stderr
# 每个exec_command都是单独作用的,先调用的命令不会影响后面命令的结果
def exec_command(
    self,
    command, # 要执行的命令
    timeout=None, # 超时时间/s
)
# 关闭连接
def close(self)
# 在当前ssh连接上,创建一个sftp会话
# 返回SFTPClient对象
def open_sftp(self)

1.2.2 Application examples

The following example shows the execution of commands on a remote host through Paramiko. In Paramiko, it should be noted that each cmd command of SSHClient works independently, and the execution of the previous cmd command will not affect the result of the latter command. For the use of the Paramiko private key, see the introduction and use of the paramiko module .

import paramiko

# 服务器地址
hostname = '114.114.114.114'
port = 22

username = 'admin'
password = '123456'
# 超时时间/s
timeout = 2
# 每条cmd命令都是单独作用的
# 进入data文件夹,并打印该目录下的文件信息
cmd = 'cd data && ls -l'

# 实例化SSHClient
client = paramiko.SSHClient()
# 加载系统主机密钥,需要在连接服务器前执行该命令
client.load_system_host_keys()
# 连接服务器
client.connect(hostname, port, username, password, timeout=timeout)

# 执行命令获得结果
(stdin, stdout, stderr) = client.exec_command(cmd)

output = stdout.readlines()
# 打印结果
for line in output:
    print(line.strip())

# 关闭连接
client.close()

1.3 Use of SFTPClient

1.3.1 Interface Introduction

SFTPClient provides the following common methods:

# --- 所有的命令都对应于linux命令
# 关闭连接
def close(self)
# 列出path路径下所有目录文件的名字,相当于执行ls
def listdir(self, path=".")
# 列出path路径下所有目录文件的信息,相当于执行ls -l
def listdir_attr(self, path=".")
# 以mode形式打开远程服务器上某个文件
def open(self, filename, mode="r")
# 删除path文件,path只能是文件
def remove(self, path)
# 将目录或文件从oldpath移动到newpath
def rename(self, oldpath, newpath)
# 创建path目录
def mkdir(self, path)
# 删除空目录path
def rmdir(self, path)
# 返回文件状态
def stat(self, path)
# 创建符号连接
def symlink(self, source, dest)
# 修改文件或目录权限
def chmod(self, path, mode)
# 修改文件拥有者
def chown(self, path, uid, gid)
# 将文件设置为指定大小,类似linux truncate命令
def truncate(self, path, size)
# 返回path的完整路径
def normalize(self, path)
# 将工作路径改为path,该命令会影响SFTPClient的其他命令
def chdir(self, path=None)
# 获得当前工作路径,如果没有调用过chdir函数,则返回None
def getcwd()
# 将本地单个文件上传到服务器
def put(self, localpath, remotepath)
# 将服务器单个文件下载到本地
def get(self, remotepath, localpath)

1.3.2 Application examples

The following example shows connecting to a remote host through Paramiko, and then managing files through SFTPClient. In Paramiko, SFTPClient is different from SSHClient, and the commands of SFTPClient will interact with each other.

import paramiko

# 服务器地址
hostname = '114.114.114.114'
port = 22

username = 'admin'
password = '123456'
# 超时时间/s
timeout = 2

# 使用with关键字就不需要主动close了
with paramiko.SSHClient() as client:
    
    client.load_system_host_keys()
    client.connect(hostname, port, username, password,timeout=timeout)
    # 打开sftp连接
    sftp_client = client.open_sftp()
    # 改变工作目录为'data'
    sftp_client.chdir('data')
    # 查看data目录下所有文件
    contents = sftp_client.listdir()
    
    for line in contents:
        print(line)
    # 获得get.py的实际路径
    remote_path = sftp_client.normalize('get.py')
    # 将remote_path下载到本地,并存为data.txt
    output_file = 'data.txt'
    # get和put函数只能对单个文件操作,如果是目录,可以用循环的方式依次处理。
    sftp_client.get(remote_path, output_file)

2 Reference

Guess you like

Origin blog.csdn.net/LuohenYJ/article/details/128510584