Windows 与 Linux:快速建立 SSH 连接

在跨平台操作中,Windows 与 Linux 的 SSH 连接是常用功能。以下是简洁实现方案。

准备工作

  1. 安装依赖:pip install paramiko
  2. 确保 Linux 开启 SSH 服务(默认端口 22),防火墙允许连接

核心代码

import paramiko
import time
import webbrowser
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options

def create_ssh_connection(hostname, port, username, password):
    """创建SSH连接"""
    client = paramiko.SSHClient()
    try:
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        print(f"正在连接到 {hostname}:{port}...")
        client.connect(hostname, port=port, username=username, password=password, timeout=10)
        print("SSH连接成功!")
        return client
    except Exception as e:
        print(f"SSH连接失败: {str(e)}")
        return None

def execute_ssh_command(client, command, wait_time=10):
    """执行SSH命令并获取输出"""
    if not client:
        return None, "未建立SSH连接"
    
    try:
        channel = client.invoke_shell()
        channel.send(command + "\n")
        time.sleep(wait_time)
        
        output = ""
        while channel.recv_ready():
            output += channel.recv(65535).decode('utf-8', errors='ignore')
        
        channel.close()
        print("命令执行完成,输出如下:")
        print(output)
        return output, ""
    except Exception as e:
        return None, f"命令执行失败: {str(e)}"

if __name__ == "__main__":
    # 配置参数
    HOST = "192.168.7.20"
    PORT = 22
    SSH_USER = "root"
    SSH_PASS = "Jsst_****"
    WEB_USER = "admin"
    WEB_PASS = "Jsst_****"
    SSH_COMMAND = "cd /opt/jsst/product/JSQ* && ./web_start.sh"
    
    # 步骤1: 建立SSH连接并执行命令
    ssh_client = create_ssh_connection(HOST, PORT, SSH_USER, SSH_PASS)
    if ssh_client:
        execute_ssh_command(ssh_client, SSH_COMMAND)
        ssh_client.close()
        print("SSH连接已关闭")
    else:
        print("无法继续执行后续操作")

注意点

  • 生产环境建议用密钥认证,替代密码
  • 可根据命令耗时调整超时参数
  • 编码问题可替换utf-8为对应字符集
posted @ 2025-08-12 10:15  菠萝包与冰美式  阅读(16)  评论(0)    收藏  举报