Connect through SSH, then run commands!
The question as it was posed:
“I have the challenge to automate a ssh login to a Linux box which asks after login then accept a EULA. So I need to press two time the arrow down key and after this the a key and a enter. Is there a way to do this with power shell?”
Why yes there is, thanks for asking!
You can do this with SendKeys.
What is SSH? SSH is a secure Shell. This is used to secure operation of network services over unsecure networks. SSH creates a secure channel over a network using a client-server, or connecting your client SSH with the SSH server.
SSH was created as a replacement to Telnet as well as unsecured remote shell like the Berkeley rsh, rlogin, and rexec protocols. These protocols send information as plain text making them susceptible to interception and disclosure using packet analyzing tools.
What is SendKeys? SendKeys is a Windows Forms Class. The SendKeys Class provides methods for sending keystrokes to an application. This Class also accepts Objects as input. With SendKeys you can send keystrokes and keystroke combinations to whatever application is currently active. It cannot be instantiated.
Start the process that way we can find the window easier. Otherwise, just change the console title and search for that instead.
Start-Process ssh Server-Name Sleep 1
To send keys to a window you need to activate that window “C:\Windows\System32\OpenSSH\ssh.exe” was the title of my window once we did a Start-Process
. This is important to know as we need to do an AppActivate
for this UNC location.
$wshell = New-Object -ComObject wscript.shell; $wshell.AppActivate('C:\Windows\System32\OpenSSH\ssh.exe')
Then what you want to send to the console. To do this we use the .Net .SendKeys
. This sends the command immediately. You can, if you choose, to wait until the process is finished by using a SendWait
. Though to be honest, in this post you wouldn’t use SendWait
.
Sleep 1 $wshell.SendKeys('{DOWN}') Sleep 1 $wshell.SendKeys('{DOWN}') Sleep 1 $wshell.SendKeys('a')
$wshell.SendKeys('mysupersecurepasswordnobodywilleverguess') $wshell.SendKeys('{ENTER}')
I will suggest you encrypt your password before using it in a script like this.
Another way of doing this would be:
#Initialize SSH connection and autologin. $StartInfo = new-object System.Diagnostics.ProcessStartInfo $StartInfo.FileName = "$pshome\powershell.exe" $StartInfo.Arguments = "-NoExit -Command `$Host.UI.RawUI.WindowTitle=`'What if I do like pie?`'" [System.Diagnostics.Process]::Start($StartInfo) Sleep 3 $wshell = New-Object -ComObject wscript.shell; $wshell.AppActivate('What if I do like pie?') Sleep 3 $wshell.SendKeys('ssh 192.168.0.0') Sleep 4 $wshell.SendKeys('{ENTER}') Sleep 3 $wshell.SendKeys('mysupersecurepasswordnobodywilleverguess') Sleep 1 $wshell.SendKeys('{ENTER}') Sleep 1 $wshell.SendKeys('lsof') Sleep 4 $wshell.SendKeys('tcpdump -i eth0') Sleep 5 $wshell.SendKeys('netstat -a | more') Sleep 6 $wshell.SendKeys('iostat')