0
因此,我正在創建一個應用程序,可以打開與遠程設備的連接並執行不同的命令。所以昨天在我離開工作之前,我在調試時遇到了一個錯誤。但是當我的應用程序忽略它並繼續進行並且沒有足夠的時間來修復它時,我決定今天就這樣做。當我想再次與我的程序建立連接時,它說它無法進行身份驗證(注意參數沒有改變)。調試錯誤後,SSH連接保持打開狀態
所以我做了一些檢查,以確定問題,登錄服務器並運行netstat後,我發現有一個活動連接到端口22,這源自我的應用程序。
不知怎的,連接沒有顯示在我的SSH管理器中,直到我重新啓動它兩次。
因此,爲了防止在生產環境中這樣的事情,我該如何防止這樣的事情。
我的Program.cs
class Program
{
static void Main(string[] args)
{
var ip="";
var port=0;
var user="";
var pwd="";
var cmdCommand="";
ConnectionInfo ConnNfo;
ExecuteCommand exec = new ExecuteCommand();
SSHConnection sshConn = new SSHConnection();
if (args.Length > 0)
{
ip = args[0];
port = Convert.ToInt32(args[1]);
user = args[2];
pwd = args[3];
cmdCommand = args[4];
ConnNfo = sshConn.makeSSHConnection(ip, port, user, pwd);
exec.executeCMDbySSH(ConnNfo, cmdCommand);
}
else {
try
{
XMLParser parser = new XMLParser();
List<List<string>> configVars = parser.createReader("C:\\Users\\myusername\\Desktop\\config.xml");
Console.WriteLine("this is from program.cs");
//iterate through array
for (int i = 0; i < configVars[0].Count; i++)
{
if ((configVars[0][i].ToString() == "device" && configVars[1][i].ToString() == "device") && (configVars[0][i + 6].ToString() == "device" && configVars[1][i + 6].ToString() == "no value"))
{
string ipAdress = configVars[1][i + 1].ToString();
int portNum = Convert.ToInt32(configVars[1][i + 2]);
string username = configVars[1][i + 3].ToString();
string passwd = configVars[1][i + 4].ToString();
string command = configVars[1][i + 5].ToString();
Console.WriteLine("making connection with:");
Console.WriteLine(ipAdress + " " + portNum + " " + username + " " + passwd + " " + command);
ConnNfo = sshConn.makeSSHConnection(ipAdress, portNum, username, passwd);
Console.WriteLine("executing command: ");
exec.executeCMDbySSH(ConnNfo, command);
}
}
}
catch (Exception e) { Console.WriteLine("Error occurred: " + e); }
}
Console.WriteLine("press a key to exit");
Console.ReadKey();
}
}
我executeCommand類:
public class ExecuteCommand
{
public ExecuteCommand()
{
}
public void executeCMDbySSH(ConnectionInfo ConnNfo, string cmdCommand)
{
try
{
using (var sshclient = new SshClient(ConnNfo))
{
//the error appeared here at sshclient.Connect();
sshclient.Connect();
using (var cmd = sshclient.CreateCommand(cmdCommand))
{
cmd.Execute();
Console.WriteLine("Command>" + cmd.CommandText);
Console.WriteLine(cmd.Result);
Console.WriteLine("Return Value = {0}", cmd.ExitStatus);
}
sshclient.Disconnect();
}
}
catch (Exception e) { Console.WriteLine("Error occurred: " + e); }
}
}
和我的課堂,我讓conenction:
public class SSHConnection
{
public SSHConnection() { }
public ConnectionInfo makeSSHConnection(string ipAdress, int port, string user, string pwd)
{
ConnectionInfo ConnNfo = new ConnectionInfo(ipAdress, port, user,
new AuthenticationMethod[]{
// Pasword based Authentication
new PasswordAuthenticationMethod(user,pwd),
}
);
return ConnNfo;
}
}
注*我沒有將我的XMLParser的類因爲它與問題無關,也沒有關於SSH的一般聯繫。