Windows 与 Linux:快速建立 SSH 连接
在跨平台操作中,Windows 与 Linux 的 SSH 连接是常用功能。以下是简洁实现方案。
准备工作
核心代码
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("无法继续执行后续操作")
 
                    
                     
                    
                 
                    
                 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号