ubuntu如何远程ssh登录Windows环境并执行测试命令

在实际的开发中有时会遇到需要在ubuntu上远程登录Windows的电脑去执行一些比较特殊的命令。这个时候就需要使用python的paramiko模块,首先去远程登录,然后再去执行对应的cmd。

1 paramiko模块简介

paramiko是一个用于在Python中实现SSH(Secure Shell)协议的模块,它提供了客户端和服务器的功能,使得你能够在网络上安全地执行命令、传输文件等。

1.1 安装paramiko

你可以使用以下命令使用pip安装paramiko:

pip3 install paramiko

1.2 paramiko基本用法

1.2.1 创建SSHClient实例

import paramiko

ssh = paramiko.SSHClient()

1.2.2 设置主机密钥策略

在连接SSH服务器之前,建议设置主机密钥策略,以便验证远程主机的身份:

ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

1.2.3 连接SSH服务器

ssh.connect(hostname='your_host', username='your_username', password='your_password')

1.2.4 执行命令

以cmd为echo "Connection test"来介绍

cmd = 'echo "Connection test"'
stdin, stdout, stderr = ssh.exec_command(cmd)

1.2.5 关闭SSH连接

ssh.close()

1.2.6 异常处理

import paramiko

try:
    # Your paramiko code here
    
    ssh.close()

except paramiko.AuthenticationException:
    print("Authentication failed, please verify your credentials")
except paramiko.SSHException as e:
    print(f"Unable to establish SSH connection: {e}")
except Exception as e:
    print(f"An error occurred: {e}")

2 windows的配置

要通过SSH连接到Windows电脑,你需要使用SSH客户端,并确保Windows电脑上已启用了OpenSSH服务。

2.1 启动OpenSSH服务

  • 打开服务管理器。你可以按Win + R打开运行对话框,然后输入services.msc并按Enter。
  • 在服务管理器中找到"OpenSSH SSH Server"服务,确保其状态为“已启动”,并将启动类型设置为“自动”。
    在这里插入图片描述

2.2 配置防火墙

  • 如果Windows防火墙启用,确保允许SSH流量。你可以在“控制面板”中的“系统和安全”下找到“Windows Defender 防火墙”,然后选择“允许应用通过防火墙”。
  • 在列表中找到“OpenSSH服务器”并确保其允许。

3 Ubuntu配置

3.1 安装ssh客户端

sudo apt-get update
sudo apt-get install openssh-client

3.2 测试是否可以远程链接到Windows

ssh username@your-windows-ip

4 paramiko使用完整测试样例

该测试用例首先使用echo "Connection test"的测试命令去测试远程链接是否确实建立。然后再去执行真是的测试命令,进入到Windows D盘的test目录,去获取test目录下的所有文件和目录,然后输出结果。

import paramiko

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

user = 'xxx'
remote_host = 'yyy'
passwd = 'zzz'
cmd = f'powershell.exe cd D:\\test; Get-ChildItem;'

try:
    ssh.connect(remote_host, username = user, password = passwd)
    print(user, '@', remote_host, ": connected successfully.")

    print(" =================== 1 ======================")
    # 执行一个简单的命令(例如:echo)来确认连接确实建立
    stdin, stdout, stderr = ssh.exec_command('echo "Connection test"')
    # 获取命令输出(如果有)
    output = stdout.read().decode('utf-8', errors='ignore').strip()
    error = stderr.read().decode('utf-8', errors='ignore').strip()

    print(" =================== 2 ======================")
    # 根据命令执行结果输出信息
    if output:
        print("Connection test succeeded:", output)
    if error:
        print("Connection test had errors:", error)

    print(" =================== 3 ======================")
    # 执行一个简单的命令(例如:echo)来确认连接确实建立
    stdin, stdout, stderr = ssh.exec_command(cmd)
    print(" =================== 3 - 1 ======================")

    # 获取命令输出(如果有)
    output = stdout.read().decode('ISO-8859-1', errors='ignore').strip()
    print(" =================== 3 - 2 ======================")
    error = stderr.read().decode('utf-8', errors='ignore').strip()
    print(" =================== 3 - 3 ======================")

    print(" =================== 4 ======================")
    # 根据命令执行结果输出信息
    if output:
        print("Connection test succeeded:", output)
    if error:
        print("Connection test had errors:", error)

    print(" =================== 5 ======================")
    # 关闭连接
    ssh.close()

except paramiko.AuthenticationException:
    print("Authentication failed, please verify your credentials")
except paramiko.SSHException as sshException:
    print("Unable to establish SSH connection: %s" % sshException)
except paramiko.BadHostKeyException as badHostKeyException:
    print("Unable to verify server's host key: %s" % badHostKeyException)
except Exception as e:
    print(e)

猜你喜欢

转载自blog.csdn.net/u014100559/article/details/134960587
今日推荐