首页 > 解决方案 > 将 python 代码与 Visual Studio c# 集成

问题描述

我在 Visual Studio 2019 中创建了 GUI。

在此处输入图像描述

那里的用户将输入用户名和密码,我必须将其传递给 python 脚本。当用户单击登录按钮时,将触发 python 脚本并显示输出。

我试过的python代码是:

import paramiko
import time

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

try:

    hostname = input("Enter host IP address: ")
    username = input("Enter SSH Username: ")
    password = input("Enter SSH Password: ")
    port = 22


    ssh.connect(hostname, port, username, password, look_for_keys=False)
    print("ssh login successfully")



#stdin,stdout,stderr = ssh.exec_command('show version')
#output = stdout.readlines()
#print(output)


    Device_access = ssh.invoke_shell()
    Device_access.send(b'environment no more \n')
    Device_access.send(b'show version\n')
    time.sleep(2)
    output = Device_access.recv(65000)
    print (output.decode('ascii'))

except:
    print("error in connection due to wrong input entered")

但是在这我没有得到如何使用 python 脚本将输入链接到 Gui c#。请让我知道我该怎么做。

提前致谢!

标签: pythonc#.netvisual-studiowindows-forms-designer

解决方案


您可以使用参数来调用您的 Python 脚本。

更改python脚本:

import paramiko
import time
import sys # Used to get arguments

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

try:

   hostname = sys.argv[1] # Skip 0th arg, since it is just the filename
   username = sys.argv[2]
   password = sys.argv[3]
   port = 22

   ssh.connect(hostname, port, username, password, look_for_keys=False)
   print("ssh login successfully")

   #stdin,stdout,stderr = ssh.exec_command('show version')
   #output = stdout.readlines()
   #print(output)


   Device_access = ssh.invoke_shell()
   Device_access.send(b'environment no more \n')
   Device_access.send(b'show version\n')
   time.sleep(2)
   output = Device_access.recv(65000)
   print (output.decode('ascii'))

except:
       print("error in connection due to wrong input entered")

并将调用脚本的 C# 代码更改为如下所示:

Process pythonScript = new Process();
pythonScript.StartInfo.FileName = "Your python script";
pythonScript.StartInfo.Arguments = $"{YouHostnameVar} {YouUsernameVar} {YourPasswordVar}"; // Start the script with the credentials as arguments
pythonScript.Start();

推荐阅读