▼点击下方卡片关注我
▲点击上方卡片关注我
想在Python里远程连接服务器,执行Shell命令?Paramiko这个库就是专门干这个的。它是Python实现SSH2协议的一个库,说白了就是能让你用Python代码来远程控制服务器,跟在终端里敲命令是一个效果。
SSH连接基本用法
连接远程服务器最常用的方式是用户名密码认证:
1
import paramiko
3
# 创建SSH客户端
4
ssh = paramiko.SSHClient()
5
# 自动添加主机密钥
6
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
8
# 连接远程服务器
9
ssh.connect(
10
hostname='192.168.1.100',
11
port=22,
12
username='root',
13
password='password123'
14
)
16
# 执行命令
17
stdin, stdout, stderr = ssh.exec_command('ls -l')
18
# 获取输出
19
result = stdout.read().decode()
20
print(result)
22
# 关闭连接
23
ssh.close()
⚠️ 小贴士:
记得处理连接异常,生产环境别裸写
用完及时关连接,别耗服务器资源
密码不要写死在代码里,该用配置文件存着
密钥认证登录
密码登录不够安全,用密钥认证更靠谱:
1
import paramiko
3
# 创建密钥对象
4
private_key = paramiko.RSAKey.from_private_key_file(
5
'/path/to/id_rsa' # 私钥文件路径
6
)
8
ssh = paramiko.SSHClient()
9
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
11
# 使用密钥连接
12
ssh.connect(
13
hostname='192.168.1.100',
14
username='root',
15
pkey=private_key # 用密钥替代密码
16
)
18
# 后续操作一样...
19
ssh.close()
批量执行命令
有时候要执行一堆命令,一个个写多麻烦:
1
def batch_execute(ssh, commands):
2
“”“批量执行命令并获取结果”“”
3
results = []
4
for cmd in commands:
5
stdin, stdout, stderr = ssh.exec_command(cmd)
6
result = {
7
'command':cmd,
8
'output':stdout.read().decode(),
9
'error':stderr.read().decode()
10
}
11
results.append(result)
12
return results
14
# 命令列表
15
commands = [
16
'df -h', # 查看磁盘使用情况
17
'free -m', # 查看内存使用
18
'top -b -n 1' # 查看进程状态
19
]
21
# 执行命令
22
results = batch_execute(ssh, commands)
24
# 打印结果
25
for result in results:
26
print(f“命令:{result['command']}”)
27
print(f“输出:\n{result['output']}”)
28
if result['error']:
29
print(f“错误:\n{result['error']}”)
30
print('-' * 50)
SFTP文件传输
SSH不光能执行命令,还能传文件:
1
def upload_file(ssh, local_path, remote_path):
2
“”“上传文件到远程服务器”“”
3
sftp = ssh.open_sftp()
4
sftp.put(local_path, remote_path)
5
sftp.close()
7
def download_file(ssh, remote_path, local_path):
8
“”“从远程服务器下载文件”“”
9
sftp = ssh.open_sftp()
10
sftp.get(remote_path, local_path)
11
sftp.close()
13
# 使用示例
14
upload_file(ssh, '/local/test.txt', '/remote/test.txt')
15
download_file(ssh, '/remote/result.log', '/local/result.log')
⚠️ 小贴士:
文件传输要考虑超时设置
大文件建议用分块传输
记得检查磁盘空间够不够
交互式命令执行
有些命令需要人机交互,比如输密码啥的:
1
import time
3
def interactive_shell(ssh, command, inputs):
4
“”“执行交互式命令”“”
5
# 获取Shell通道
6
channel = ssh.invoke_shell()
8
# 发送命令
9
channel.send(command + '\n')
10
time.sleep(0.5) # 等待命令响应
12
# 处理交互输入
13
for user_input in inputs:
14
channel.send(user_input + '\n')
15
time.sleep(0.5)
17
# 获取所有输出
18
output = ''
19
while channel.recv_ready():
20
output += channel.recv(1024).decode()
22
channel.close()
23
return output
25
# 使用示例
26
inputs = ['yes', 'new_password', 'new_password']
27
result = interactive_shell(ssh, 'passwd', inputs)
差不多就这些,Paramiko还有不少高级功能,比如连接代理、压缩传输啥的。不过掌握这些基本操作,日常自动化运维应该够用了。最好配合异常处理和重试机制,生产环境用起来稳稳的。
往期回顾
点赞分享
让钱和爱流向你