How to Automate Remote SSH Control of Computers with Expect Scripts « Null Byte :: WonderHowTo

If you're getting into automation, Bash scripting is usually the way to go. However, there are a couple of limitations, and one of them is logging into another device like aRaspberry Piand running a script automatically. To help in those situations, we're going to automate delivering an SSH payload with an "expect" script.Bash scripting is more like duct-taping things together, so it isn't able to do everything, including predicting and then reacting to certain variables. So we're going to use an "expect" script to log in to our Raspberry Pi and automatically shut it down. We could also adapt the script to pass pretty much any payload we want to the Pi.It's a pretty awesome use of an expect script, and there are lots of different things you can do with it, so know that our guide is just scratching the surface of how you can take an expect script and use it to actually do things that otherwise would require a lot more user interaction.Don't Miss:Discover & Attack Raspberry Pis Using Default CredentialsTo follow along, you'll need a Linux computer running something like Kali or Ubuntu — even a Mac will work. Also, you'll need to have the arp-scan and expect tools installed. On Kali, you can do that withapt install arp-scan expect, and you'll be set.Step 1: Create the Expect ScriptExpect scripts are usually used in conjunction with Bash scripts to automate certain things like scanning a network or delivering a payload. Because the two work so well together, it's possible to automate all sorts of interesting things. Here, we're going to be knocking anyRaspberry Pison the network using default credentials off the network.Expect is a unique scripting language that emulates keystrokes by responding to expected responses from a local or remote system. Think of Expect as an automated, virtual you.—Admin MagThe expect.exp script we're showing off is incorporated into our trigger.sh script, so we need to create it first. If you want, start a new directory (mkdir) andnanointoexpect.expto start the script draft. Then, copy and paste the script seen below into it, hitControl-Xto exit,Yto add it to buffer, andEnterto save the file.#!/usr/bin/expect -f

set timeout 20

set ip [lindex $argv 0]

set user [lindex $argv 1]

set password [lindex $argv 2]

spawn ssh "$user\@ip" "reboot"

expect "assword:"

send "$password\r";

interactStep 2: Create the Trigger Bash ScriptBefore we dive into what all of that is doing, let's create trigger.sh, our Bash script. So in the same directory, usenanoto create a newtrigger.shfile. In it, copy and paste the following code. HitControl-Xto exit,Yto add it to buffer, andEnterto save the file.#! bin/bash
echo What is the passcode?
read loginpass
expect expect.exp $(arp-scan -l | grep Raspberry | awk '{print $1}') root $loginpassYou can see that it starts with the standard shebang (#!) and thebin/bash; this just forces the Bash language to be used for the rest of the script.On the second line, we useechoto show the user a prompt that says, "What is the passcode?" We thenreadwhatever the input was and save it as aloginpassvariable.Lastly, trigger.sh opens ourexpectscript, where we're essentially passing three variables to it. As discussed ina previous Bash lesson, the parentheses ( ) mean that everything within it will happen before continuing with the rest of the commands in the one-liner, and a dollar sign ($) indicates a variable. So whatever is the answer to the content inside the parentheses will be a variable.So, the first part of the equation is that anarp-scanis run. This sends out ARP packets to hosts on the local network, then displays its responses. Then,grep, a command-line utility for searching through text, looks at the scan results for the wordRaspberryto hunt for Raspberry Pis. Next,awk, another tool for searching through text, looks for the microcontroller's IP address found from the arp-scan and grep, andprintprints the final results.After all of that is done, it passes the usernamerootto the Pi, which is the default on Pis. This is slightly inspired by the Raspberry Hunter, orrpi-hunter, which is something that hunts for Pis using default credentials on the network, attempts to log into them, and then send payloads.Lastly, it passes the password to the Pi via the password that the user input and stored as theloginpassvariable.Don't Miss:Write Your Own Bash Scripts to Automate Tasks on LinuxStep 3: Run the Trigger Bash ScriptNow, let's run the script. After it starts, you'll be asked for the enemy's passcode. Let's first see what happens when we enter the wrong password.~$ bash trigger.sh

What is the enemy passcode?
kdsjsdgliyea

spawn ssh root@192.168.1.183 reboot
The authenticity of host '192.168.1.183 (192.168.1.183)' can't be established.
ECDSA key fingerprint is SHA256:wG9YqeFrX90eEjV9+APhnxVkA3DduuZ+d9RbypwKFp4E.
Are you sure you want to continue connecting (yes/no)? yes

kdsjsdgliyea
yes
Please type 'yes' or 'no': yes

Warning: Permanently added '192.168.1.183' (ECDSA) to the list of known hosts.
Welcome to meye-16b312e&!
root@192.168.1.183's password:As you can see, it tried spawning an SSH script to pass therebootcommand to theRaspberry Pi. Since we gave it the wrong password, it didn't work, so then it asked us if we wanted to continue, which was a "yes." Next, it asks us if we wanted to log in. We said "yes," and it attempted to log in to the Raspberry Pi, but it couldn't because it had the wrong password.Though it failed, it could still find a Raspberry Pi on the network and tried to SSH into it. Now, let's see what happens when we have the real password. One thing to keep a note of is that if you're logging into something via SSH for the first time, it'll first ask you to confirm, and this will probably break the Bash script. To make sure it works, log in first.~$ bash trigger.sh

What is the enemy passcode?
starstar

spawn ssh root@192.168.1.234 reboot
root@192.168.1.234's password:
Connection to 192.168.1.234 closed by remote host.As you can see, it detected a Raspberry Pi on the network successfully, spawned an SSH session, and gave it therebootcommand. Then, it entered the password that was entered by the user as a variable. After logging in, it closed the host, causing the Raspberry Pi to reboot and kick us out.How the Expect Script WorksWe detailed the trigger.sh file and what it does, but now let's look at the expect.sh code to see what it does with all of the information passed by the Bash script.First, it starts with the standard shebang (#!), theusr/bin/expect, and tack f (-f); this just forces the Expect interpreter to be used for the rest of the script.Next, wesetatimeoutof20seconds, so the script times out after that amount of time. Then, we have theset ipline, which takes the first argument passed to expect.sh, and that would be the arp-scan results in trigger.sh — the Raspberry Pi's IP address. Thelindex $argv 0just tells it to look for the first argument passed, and it starts with zero, which is important to remember.We then have theset userline, which looks for the second argument passed, in this case,root. After that, theset passwordline looks for the third argument passed, in this case, the user's password that was supplied to trigger.sh.Now things start getting interesting. Expect scripts can spawn processes, and here we're spawning an SSH process (spawn ssh) and using the variables the same way we would in Bash pretty much. It takes the$uservariable, root, then adds@with the$ipvariable, the Pi's IP address. That's how it connects to the Pi. Then, as soon as it gets logged in, it issues arebootcommand.However, before all that can happen, we need to use theexpectpart of the script, where we are looking for something that is basically coming to us and typing the stringassword. That's funny, but there's a reason we do that. If it is a capital "P" or a lowercase "p," it really doesn't matter depending on what server it is. It's always going to ask us for a password. So unless it's in all caps, which is a little bit less probable, then we're likely to get most of the different ways of asking us for a password.So what the script is doing is expecting a request, or a text string, to say "password" or "Password." If it gets that, then it goes ahead and sends the result, which, in our case, is the password the user typed way back at our Bash script. Theinteractline puts the whole script into play.You Can Do a Lot with Expect ScriptsExpect scripts are not interactive, so we have to use Bash scripts to pass in information. For example, we can't have user input directly in this expect script. It's very annoying that we can't, so as a result, it works very well to have a Bash script that gathers all the information you need, passes it to an expect script, and then that expects script will automate something.Overall, expect scripts are handy for creating chatbots or dealing with anything where you have an input you're expecting and a response you want to automate. Now, combined with Bash scripts, you can automate all sorts of powerful tools, so this is just a beginning, and I hope you can use it to create some really interesting automations.Don't Miss:How to Write Your Own Bash Script to Automate ReconWant to start making money as a white hat hacker?Jump-start your hacking career with our2020 Premium Ethical Hacking Certification Training Bundlefrom the newNull Byte Shopand get over 60 hours of training from cybersecurity professionals.Buy Now (90% off) >Other worthwhile deals to check out:97% off The Ultimate 2021 White Hat Hacker Certification Bundle99% off The 2021 All-in-One Data Scientist Mega Bundle98% off The 2021 Premium Learn To Code Certification Bundle62% off MindMaster Mind Mapping Software: Perpetual LicenseCover photo by Retia/Null ByteRelatedHow To:Run Your Favorite Graphical X Applications Over SSHHow To:Configure a Reverse SSH Shell (Raspberry Pi Hacking Box)How To:Automate Hacking on the Raspberry Pi with the USB Rubber DuckySPLOIT:How to Make an SSH Brute-Forcer in PythonHow To:Spy on SSH Sessions with SSHPry2.0How To:Share Your LAN Minecraft World with Your Linux-Savvy FriendsHow To:Create an SSH tunnel for your Mac Mini serverHow To:Discover & Attack Raspberry Pis Using Default Credentials with Rpi-hunterHack Like a Pro:How to Remotely Record & Listen to the Microphone on Anyone's ComputerHow To:Haunt a Computer with SSHHack Like a Pro:Linux Basics for the Aspiring Hacker, Part 15 (Creating a Secure Tunnel to MySQL)How To:Use SSH Local Port Forwarding to Pivot into Restricted NetworksHacking Windows 10:How to Use SSH Tunnels to Forward Requests & Hack Remote RoutersHow To:Automate Brute-Force Attacks for Nmap ScansRasberry Pi:Connecting on ComputerHow To:Use Remote Port Forwarding to Slip Past Firewall Restrictions UnnoticedHow To:Set Up a Headless Raspberry Pi Hacking Platform Running Kali LinuxHow To:Access & Control Your Computer Remotely Using Your iPhoneHow To:Use Common Features of Windows Command PromptHow To:Locate & Exploit Devices Vulnerable to the Libssh Security FlawHow To:Easily Detect CVEs with Nmap ScriptsHow To:Access & Control Your Computer Remotely with Your Nexus 5Hacking Windows 10:How to Turn Compromised Windows PCs into Web ProxiesHow To:Use the Chrome Browser Secure Shell App to SSH into Remote DevicesHow To:Perform Network-Based Attacks with an SBC ImplantHacking macOS:How to Create a Fake PDF Trojan with AppleScript, Part 1 (Creating the Stager)How To:Remotely Control Computers Over VNC Securely with SSHHow To:Safely Log In to Your SSH Account Without a PasswordHow To:Create a Free SSH Account on Shellmix to Use as a Webhost & MoreHow To:Push and Pull Remote Files Securely Over SSH with PipesHow To:Create an SSH Tunnel Server and Client in LinuxHow To:Create a Reverse Shell to Remotely Execute Root Commands Over Any Open Port Using NetCat or BASHNews:The Money Making MacroNews:Remote Control Demolition Derby IllusionNews:Hide & Seek Airbag ExplosionNews:Underwater Remote Operated VehicleNews:New AF100 Remote Helicopter FootageNews:In Just a Clik, Turn Your Smartphone into a YouTube Remote for Any Web DisplayUDP Flooding:How to Kick a Local User Off the NetworkHow To:How Hackers Use Your IP Address to Hack Your Computer & How to Stop It