Paramiko 说明
Paramiko 组件
paramiko.Transport
paramiko.SSHClient
区别
SSHClient()
属性(Attributes)
方法(Methods)
连接方法(Connection Methods)
命令执行方法(Command Execution)
创建新的通道
client.get_transport().open_session(): 这一行代码的作用是创建一个新的SSH会话(session)。它首先从SSH客户端(client)获取一个传输对象(transport),然后通过该传输对象创建一个新的会话(session)。会话用于管理连接生命周期中的所有数据交换,例如发送命令、接收响应等。在这个会话上,可以执行一些会话相关的命令。
client: 这是一个已经建立的 SSHClient 实例,用于管理 SSH 连接和操作。
get_transport(): 这是用于获取底层的传输(transport)对象的方法,transport 对象处理底层的数据传输和连接管理。
open_session(): 这是在传输(transport)上创建一个新的会话(session)通道。通过这个通道,可以执行远程命令、交换数据等。
channel: 这是一个被创建的会话通道对象,你可以使用它来执行一系列操作,比如执行命令、传输文件等。通常,你会在这个通道上执行具体的操作。
- 1.
- 2.
- 3.
- 4.
- 5.
import paramiko
# 创建SSH客户端并连接到远程服务器
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 自动接受未知主机密钥(仅用于示例)
client.connect('hostname', username='username', password='password') # 使用实际的主机名、用户名和密码替换这里的信息
# 创建一个会话通道(channel)
channel = client.get_transport().open_session()
# 通过会话通道发送命令并获取输出
channel.exec_command('ls -l') # 例如,执行一个'ls -l'命令
# 读取输出
output_stdout = channel.recv(4096).decode() # 读取输出(示例中假设最大输出大小为4096字节)
output_stderr = channel.recv_stderr(4096).decode()
print("命令执行结果:")
print(output_stdout) # 输出标准输出
print(output_stderr) # 输出标准错误输出
# 执行第二条命令
channel.exec_command('pwd') # 例如获取当前工作目录
output = channel.recv(4096).decode() # 读取命令输出
print(output) # 打印第二条命令的输出内容
# 关闭会话通道
channel.close()
# 关闭SSH连接
client.close()
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
SFTP 方法(Secure File Transfer Protocol):
import paramiko
remote_host = 'xxxxx'
user_name = 'xxxxx'
password = 'xxxxx'
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接到远程主机
client.connect(remote_host, username=user_name, password=password,port=22, timeout=5)
# 创建 SFTP 会话
sftp = client.open_sftp()
# 本地文件路径和远程路径
local_path = r'G:\kylinos.repo'
remote_path = '/tmp/kylinos.repo'
try:
# 上传本地文件到远程服务器
sftp.put(local_path, remote_path)
print("File uploaded successfully.")
except Exception as e:
print(f"Upload failed: {str(e)}")
try:
# 下载远程文件到本地
sftp.get(remote_path, r'F:\work\python\files\kylinos.repo')
print("File downloaded successfully.")
except Exception as e:
print(f"Download failed: {str(e)}")
# 列出远程目录内容
directory_contents = sftp.listdir('/tmp')
print(directory_contents)
# 关闭 SFTP 会话和 SSH 连接
sftp.close()
client.close() # 关闭连接
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
关闭连接
示例
import paramiko
import logging
def execute_ssh_commands(hostname, port, username, password, commands):
# 设置日志记录
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
all_output = {}
hosts_info = {}
try:
logging.info(f"Connecting to {hostname}...")
client.connect(hostname, port, username, password, timeout=10)
for command in commands:
print(f"Executing command: {command}")
stdin, stdout, stderr = client.exec_command(f"echo '{password}' | sudo -S -p '' {command}", get_pty=False,
timeout=10)
command_output = []
command_error = []
out_msg = stdout.read().decode('utf-8')
if out_msg:
logging.info(out_msg)
command_output.append(out_msg)
err_msg = stderr.read().decode('utf-8')
if err_msg:
logging.error(err_msg)
command_error.append(err_msg)
# 检查命令执行状态
exit_status = stdout.channel.recv_exit_status()
if exit_status == 0:
command_status = 'Success'
else:
command_status = 'Failed'
all_output[command] = {
'stdout': command_output,
'stderr': command_error,
'status': command_status
}
hosts_info[hostname] = all_output
return hosts_info
except Exception as e:
logging.error(f"An error occurred: {e}")
return {hostname: {'error': str(e)}}
finally:
if client:
client.close()
logging.info("Connection closed.")
# 定义主机信息和命令列表
remote_host = ''
remote_port =
remote_username = ''
remote_password = '1'
ports =
commands_to_execute = [
"bash -c 'for i in $(docker ps | grep -v CONT | awk \"{print \$1}\"); do docker exec -t $i bash -c \"netstat -nlptu | grep -v tcp6 |egrep \"" + str(
ports) + "\"\"; done | wc -l'",
"ls",
"date"
]
# 连接到 SSH,依次执行多个命令并获取结果
result = execute_ssh_commands(remote_host, remote_port, remote_username, remote_password, commands_to_execute)
print(result)
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
- 42.
- 43.
- 44.
- 45.
- 46.
- 47.
- 48.
- 49.
- 50.
- 51.
- 52.
- 53.
- 54.
- 55.
- 56.
- 57.
- 58.
- 59.
- 60.
- 61.
- 62.
- 63.
- 64.
- 65.
- 66.
- 67.
- 68.
- 69.
- 70.
- 71.
- 72.
- 73.
- 74.
- 75.
- 76.
- 77.
参考文档
https://github.com/paramiko/paramiko