Paramiko是一个Python实现的SSHv2协议库,可以用于远程连接Linux服务器并执行命令。下面我将详细介绍如何使用Paramiko实现这一功能。
首先需要安装paramiko库:
pip install paramiko
import paramiko
# 创建SSH客户端实例
ssh = paramiko.SSHClient()
# 自动添加主机密钥(生产环境应考虑更安全的方式)
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接服务器
ssh.connect(hostname='服务器IP',
port=22,
username='用户名',
password='密码')
# 执行命令
stdin, stdout, stderr = ssh.exec_command('ls -l')
# 获取命令输出
output = stdout.read().decode('utf-8')
error = stderr.read().decode('utf-8')
# 打印输出
print("输出:", output)
if error:
print("错误:", error)
# 关闭连接
ssh.close()
# 使用私钥文件连接
private_key = paramiko.RSAKey.from_private_key_file('/path/to/private_key.pem')
ssh.connect(hostname='服务器IP',
port=22,
username='用户名',
pkey=private_key)
# 使用分号分隔多个命令
commands = """
cd /tmp;
ls -l;
pwd;
"""
stdin, stdout, stderr = ssh.exec_command(commands)
transport = paramiko.Transport(('服务器IP', 22))
transport.connect(username='用户名', password='密码')
ssh = paramiko.SSHClient()
ssh._transport = transport
# 执行命令...
stdin, stdout, stderr = ssh.exec_command('uname -a')
# 完成后关闭
transport.close()
# 创建交互式shell
channel = ssh.invoke_shell()
channel.send('sudo ls /root\n')
channel.send('密码\n') # 如果是sudo需要密码
import time
time.sleep(1) # 等待命令执行
output = channel.recv(9999).decode('utf-8')
print(output)
import paramiko
from getpass import getpass
def remote_execute(host, port, username, password=None, key_path=None, command=''):
try:
# 创建SSH客户端
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接服务器
if key_path:
private_key = paramiko.RSAKey.from_private_key_file(key_path)
ssh.connect(hostname=host, port=port, username=username, pkey=private_key)
else:
ssh.connect(hostname=host, port=port, username=username, password=password)
# 执行命令
stdin, stdout, stderr = ssh.exec_command(command)
# 获取输出
output = stdout.read().decode('utf-8').strip()
error = stderr.read().decode('utf-8').strip()
return {
'output': output,
'error': error,
'status': 'success'
}
except Exception as e:
return {
'output': '',
'error': str(e),
'status': 'failed'
}
finally:
# 确保连接关闭
if 'ssh' in locals():
ssh.close()
# 使用示例
if __name__ == '__main__':
host = input("输入服务器IP: ")
port = 22
username = input("输入用户名: ")
use_key = input("使用密钥认证? (y/n): ").lower() == 'y'
if use_key:
key_path = input("输入私钥路径: ")
password = None
else:
key_path = None
password = getpass("输入密码: ")
command = input("输入要执行的命令: ")
result = remote_execute(
host=host,
port=port,
username=username,
password=password,
key_path=key_path,
command=command
)
print("\n执行结果:")
if result['status'] == 'success':
if result['output']:
print("输出:\n", result['output'])
if result['error']:
print("错误:\n", result['error'])
else:
print("执行失败:", result['error'])
AutoAddPolicy
,而应该预先验证主机密钥认证失败:
PasswordAuthentication yes
)连接超时:
命令无输出:
cd
不会产生输出)-v
参数查看详细执行过程通过以上方法,你可以灵活地使用Paramiko库在Python中实现远程执行Linux命令的功能。