Python实现ssh自动连接
此文章为了实现不同PC端可以通过Python代码来代替终端命令实现ssh连接
一,终端连接
以下先介绍传统的连接方式:
1,确保网络连通性
-  两台设备需在同一局域网或能通过互联网互相访问(如需公网访问,需配置端口转发)。 
-  检查连通性(例如设备A ping 设备B): 
ping <设备B的IP地址>2. 确认SSH服务运行
在设备B(被连接的设备)上安装SSH服务(如未安装。以Linux为例):
sudo apt install openssh-server 启动ssh服务:
sudo systemctl start sshd  检查服务状态:
sudo systemctl status sshd3. 获取设备B的IP地址
ifconfig4.防火墙设置
确保设备B的防火墙允许SSH端口(默认22):
sudo ufw allow 225. 从设备A发起SSH连接
ssh <用户名>@<设备B的IP地址>例如
ssh user@192.168.1.100二,Python代码连接
要通过 Python 代码自动实现 SSH 连接,可以使用 paramiko 库(最常用的 SSH 客户端库,支持 远程命令执行、SFTP文件传输 和 端口转发)
1.安装paramiko库
pip install paramiko2.导入库并创建ssh客户端
import paramiko# 创建SSH客户端对象
ssh = paramiko.SSHClient()3.设置主机密钥策略
SSH 连接时,客户端会验证服务器的主机密钥(防止中间人攻击)。
 paramiko 提供几种策略:
-  AutoAddPolicy:自动添加未知主机密钥(方便测试,但安全性较低)。
-  WarningPolicy:未知主机时发出警告(默认)。
-  RejectPolicy:拒绝未知主机(最安全,需提前手动信任)。
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 4.建立ssh连接
分为密码认证和密钥认证两种
密码认证:
host = "192.168.1.100"  # 目标服务器IP
port = 22               # SSH端口(默认22)
username = "ubuntu"     # 用户名
password = "your_password"  # 密码(生产环境避免硬编码)try:ssh.connect(host, port, username, password)print("SSH连接成功!")
except paramiko.AuthenticationException:print("认证失败:用户名或密码错误")
except paramiko.SSHException as e:print(f"SSH连接失败: {e}")
except Exception as e:print(f"未知错误: {e}")密钥认证:
密钥认证就是将密码放到一个权限文件,这样更安全
private_key_path = "~/.ssh/id_rsa"  # 私钥路径try:private_key = paramiko.RSAKey.from_private_key_file(private_key_path)ssh.connect(host, port, username, pkey=private_key)print("SSH密钥认证成功!")
except paramiko.SSHException as e:print(f"密钥认证失败: {e}")~/.ssh/id_rsa 文件是 SSH 密钥对中的私钥文件,通常由用户手动生成。使用如下ssh-keygen命令生成
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"-  -t rsa:指定密钥类型为 RSA。
-  -b 4096:密钥长度(建议 4096 位)。
-  -C:注释(通常用邮箱标识密钥用途)。
生成过程如下:
Generating public/private rsa key pair.
Enter file in which to save the key (/home/your_user/.ssh/id_rsa):  # 直接回车(默认路径)
Enter passphrase (empty for no passphrase):  # 可选:设置密钥密码(增强安全性)
Enter same passphrase again:  # 确认密码也可以使用paramiko生成密钥,同时密钥需要设置权限,这是因为SSH 要求密钥文件权限严格受限,否则会报错。这里不做更详细解释,一般使用密码认证就足够了
5.执行远程命令
使用 exec_command() 执行命令,返回 stdin, stdout, stderr 三个流:
command = "ls -l /tmp"  # 示例命令stdin, stdout, stderr = ssh.exec_command(command)# 获取命令输出
output = stdout.read().decode()  # 标准输出
error = stderr.read().decode()   # 错误输出print("标准输出:\n", output)
if error:print("错误输出:\n", error)6.关闭ssh
ssh.close()  # 显式关闭连接完整实例:密码认证+执行命令
import paramikodef ssh_exec_command(host, username, password, command):ssh = paramiko.SSHClient()ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())try:ssh.connect(host, username=username, password=password)stdin, stdout, stderr = ssh.exec_command(command) # 返回stdin, stdout, stderr三个对
#象。stdin用于向远程命令发送输入数据(如果需要交互式输入),比如stdin.write(),但大多数命令不需要
#输入。stdout读取命令的正常输出(即命令打印到终端的内容),stderr读取命令的错误输出(如报错信
#息)。 stdout.read().decode()读取读取全部输出(二进制需解码)output = stdout.read().decode() # error = stderr.read().decode()if output:print("命令输出:\n", output)if error:print("错误:\n", error)except Exception as e:print(f"SSH操作失败: {e}")finally:ssh.close()# 使用示例
ssh_exec_command("192.168.1.100", "ubuntu", "your_password", "df -h")