通过visual basic应用程序在unix服务器上执行命令

时间:2013-01-21 18:31:38

标签: vb.net bash shell unix

我需要帮助使用Visual Basic应用程序在Unix服务器上执行命令。我使用的是Visual Basic Express 2010。

P.S。我可以使用systems.net.sockets连接到服务器,但无法发送命令来执行。

我愿意尝试任何不同的方法,我只需要知道如何做到这一点。

1 个答案:

答案 0 :(得分:7)

我可以想到两种方法来实现这个目标:

  1. 在系统上安装了像Putty这样的程序,并使用Putty对服务器(应用程序外部)进行SSH调用,并以这种方式发送命令。这将需要您的应用程序的一些提升权限,因为它将必须直接访问系统。在我看来,这是“丑陋”的方式。

  2. 找到一个VB SSH库。我找到this one,但必须有更多。这将允许您创建到Unix框的SSH连接并传递您要运行的命令。这将是“最好的”方式。

  3. 编辑:

    CSHARP并不重要。您可以下载Visual C#2010 Express并打开Renci.SshNet并构建它。一旦它构建完成,你就会获得一个dll,然后你可以添加它作为VB项目的参考。有点痛苦,但使用Express版本需要付出很小的代价。 :)

    以下是使用构建运行在Visual C#2010 Express中打开的ssh库的屏幕截图。您可以在左下方看到“构建成功”: screenshot of build

    将它作为参考后,您可以使用该库与服务器建立ssh连接并运行命令。这是一些示例代码。我创建了一个VB Web应用程序,添加了dll作为参考,并将一个click事件添加到一个按钮,将结果吐出到标签控件中:

    Protected Sub btnSSHTest_Click(sender As Object, e As EventArgs) Handles btnSSHTest.Click
    
        'Create the objects needed to make the connection'
        Dim connInfo As New Renci.SshNet.PasswordConnectionInfo("hostname", "username", "password")
        Dim sshClient As New Renci.SshNet.SshClient(connInfo)
    
        'Need to hold the command'
        Dim cmd As Renci.SshNet.SshCommand
    
    
        Using sshClient
            'connect to the server'
            sshClient.Connect()
    
            'Run the command and put the results into the cmd object. In this case'
            'I am just running a directory list'
            cmd = sshClient.RunCommand("ls -lthr")
    
            'my web page had a label control on it. I placed the results of the cmd into'
            'the label'
            lblResult.Text = cmd.Result
    
            'Close the connection.'
            sshClient.Disconnect()
        End Using
    
    End Sub
    

    编辑:

    为了确保它在非Web应用程序中运行,我在使用Vb 2010 express创建的Windows窗体应用程序中做了示例。我在表单中添加了一个按钮和一个标签,并将上面的代码添加到按钮单击事件中。然后我添加了对我从C#2010 Express创建的DLL(库)的引用。

    这是添加引用的屏幕截图: how to add a reference

    以下是项目属性的屏幕截图,显示已添加引用: screenhot showing the reference in the project

    接下来,我运行了项目并单击了按钮。建立了与unix盒的连接,并将命令的结果(在本例中为'ls -lthr')放在标签中。我以root身份登录(不推荐)并从/ root /目录运行命令。这就是为什么那里没有多少。 application running

相关问题