How to connect to Linux server using python

1. Install the paramiko library

pip install paramiko

2. Use the paramiko library to connect to linux

#导入库
import paramiko

#创建一个sshclient对象
ssh = paramiko.SSHClient()

#允许连接不在know_host中的主机
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

#连接主机
ssh.connect(hostname="服务器ip",port=22,username="用户名",password="密码")

#执行命令
ssh_in,ssh_out,ssh_error = ssh.exec_command('ps -ef')
"""
这里会返回三个结果
ssh_in 标准输入,也就是我们输入的命令
ssh_out 标准输出,命令执行的结果
ssh_error 命令执行过程中的错误
"""

#读取结果
res,error = ssh_out.read(),ssh_error.read()
result = res if res else error
print(result.decode())

#关闭client对象
ssh.close()

picture

3. Use the paramiko library to upload and download files

import paramiko

# 连接服务器
transport = paramiko.Transport(('hostname',22))
transport.connect(username='账号',password='密码')

ftp = paramiko.SFTPClient.from_transport(transport)  # 定义一个ftp实例

ftp.get('服务器文件路径',' 本地文件路径')   # 下载文件
ftp.put('本地文件路径', '服务器文件路径')  # 上传文件

ftp.close()
transport.close()

Finally, I would like to thank everyone who reads my article carefully. Reciprocity is always necessary. Although it is not a very valuable thing, if you can use it, you can take it directly:

Insert image description here

This information should be the most comprehensive and complete preparation warehouse for [software testing] friends. This warehouse has also accompanied tens of thousands of test engineers through the most difficult journey. I hope it can also help you!   

Guess you like

Origin blog.csdn.net/qq_48811377/article/details/132807878