This question already has an answer here:
Providing input/subcommands to a command (cli) executed with SSH.NET SshClient.RunCommand

(1个答案)


在8个月前关闭。




我需要你的帮助。
ssh连接成功。
我已经检查了此命令-> Pass:pc1.RunCommand(“echo'!123123'| sudo -S reboot”)

所以我尝试了其他 Action 。

我需要运行linux shell脚本文件。

删除:pc1.RunCommand(“echo'!123123'| sudo -S重新启动”)
添加:pc1.RunCommand(“cd〜/ ryu / 123.sh”);
但是此命令不起作用。 (油灰通过)
有人知道吗?

谢谢。
        PasswordConnectionInfo info1 = new PasswordConnectionInfo("server ip", 22, "user", "password");
        info1.Timeout = TimeSpan.FromSeconds(5);
        SshClient pc1 = new SshClient(info1);
        try
        {
            if (checkBox1.Checked == true)
            {
                pc1.Connect();
                if (pc1.IsConnected)
                {
                    pc1.RunCommand("echo '!123123' | sudo -S reboot"); <--- this command pass
                    pc1.RunCommand("cd ~/ryu/123.sh"); <--- this command not working
                }

最佳答案

假设.sh文件的权限已经可以执行(chmod a + x)。我认为第二个命令很好用。您只需要“读取”“输出”即可。
这就是我实现Renci.SSHNet的方式:希望对您有所帮助。

$sshSession = New-Object Renci.SshNet.SshClient($serverIp, 22, $username, $password)
$sshSession.Connect()  # check if connected first if you want -
$stream = $sshSession.CreateShellStream($serverIp, 500, 100, 1024, 600, 1024)
$reader = New-Object System.IO.StreamReader($stream)
$writer = New-Object System.IO.StreamWriter($stream)
$writer.AutoFlush =$true
$lineMatch = "[root@server1]#"  # sample only; change this to the text you are seeing on your terminal
$writer.WriteLine("pwd") # print working directory
Start-Sleep -Seconds 1
# this will loop until the the output is empty
do{
    $line = $reader.ReadLine()
    if(!([string]::IsNullOrEmpty($line))){
        Write-Host $line  # print the current line
    }
}while($line -ne $lineMatch)

关于c# - 如何通过ssh运行linux shell脚本文件? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60518767/

10-09 04:47