Linux expect ssh пример

How to use bash/expect to check if an SSH login works

My team manages many servers, and company policy dictates that the passwords on these servers must be changed every couple of weeks. Sometimes, our official database of passwords gets out of date for whatever reason (people forget to update it, usually), but we cannot identify this sometimes until months later, since we don’t consistently use every server. I want to write a script that will scrape the passwords from the database, and use those passwords to attempt an (ssh) login to each server every night, and send an email with the results to the team. I am able to scrape the database for login information, but I’m not sure how to check whether ssh login was successful or not in expect. I cannot use public key authentication for this task. I want password authentication so I can verify the passwords. I disable public-key authentication by specifying the following file:

PasswordAuthentication=yes PubkeyAuthentication=no 
# $1 = host, $2 = user, $3 = password, $4 = config file expect -c "spawn ssh $2@$1 -F $4 expect -re \".*?assword.*?\" send \"$3\n\" . send \'^D\'" 

I thought maybe exit status could indicate the success? Couldn’t find anything in the man pages though.

Who changes the password? Perhaps they should also be responsible for updating the database. Putting the password into this sort of script seems to defeat the purpose of changing the password frequently.

The password does not go into the script. The passwords are scraped from a database and passed as command-line arguments to the script, which makes perfect sense to me. And even though people have the responsibility to update the database, they often do not. This is a sanity check to make sure all the passwords in the database are correct.

Источник

Bash/Expect Script for SSH

I am new to Expect and scripting in general. I am trying to make a few scripts to make my life a bit easier when pulling network device configurations. I managed to create a basic Expect script to SSH to a device and save the configuration. I want to expand upon this and allow the script to connect to a number of IP addresses instead of just one like I have right now. I have a file named list.txt with a few different IP addresses with each IP address on a separate line. What would I need to do to have the Expect script connect to each of these IP addresses and perform the rest of the tasks in the script as well? Here is the Expect script I have so far:

#!/usr/bin/expect -f # Tells interpreter where the expect program is located. This may need adjusting according to # your specific environment. Type ' which expect ' (without quotes) at a command prompt # to find where it is located on your system and adjust the following line accordingly. # # # Use the built in telnet program to connect to an IP and port number spawn ssh 192.168.1.4 -l admin # # The first thing we should see is a User Name prompt #expect "login as:" # # Send a valid username to the device #send "admin" # # The next thing we should see is a Password prompt expect "Password:" # # Send a valid password to the device send "password\n" # # If the device automatically assigns us to a privileged level after successful logon, # then we should be at an enable prompt expect "Last login:" # # Tell the device to turn off paging # # After each command issued at the enable prompt, we expect the enable prompt again to tell us the # command has executed and is ready for another command expect "admin@" # # Turn off the paging send "set cli pager off\n" # # Show us the running configuration on the screen send "show config running\n" # # Set the date. set date [timestamp -format %C%y%m%d] # # Test output sent to file with a timestamp on end #-noappend will create a new file if one already exists log_file -noappend /home/test.cfg$date # expect "admin@" # # Exit out of the network device send "exit\n" # # The interact command is part of the expect script, which tells the script to hand off control to the user. # This will allow you to continue to stay in the device for issuing future commands, instead of just closing # the session after finishing running all the commands.`enter code here` interact 

Do I need to integrate this with a Bash script? If so, is it possible to read one line of the list.txt file, use that as the IP address/host variable and then read the next and repeat?

Читайте также:  Kali linux откат системы

Источник

Making Expect scripts for SSH Authentication and Privilege Elevation

Alexander V. Leonov

Alexander V. Leonov

Expect can help you to automate interactive console applications. For example, expect script can go to some Linux host via SSH with password authentication, make additional authentication procedures (su, sudo) to elevate privileges and execute some commands. Like Vulnerability and Compliance management products do during the active Linux scanning, right? 🙂 For example you can get the list of installed packages and make Vulnerability Assessment without Vulnerability Scanner.

Expect SSH exec

Actually, the tool is pretty old. It was presented more than 20 years ago! And perhaps now it makes more sense to use python scripts, for example paramiko with paramiko-expect. Or even use some software provisioning tool, like Ansible. But my fun was in creating (generating?) a small old-school scripts that could be sent to any remote host (with expect installed) to gather information from the accessible hosts.

So, the installation is trivial:

Expect scripting language is an extension to the Tcl. In this language you can set the variables, commands that you want to ran, the lines that you expect from the server response and the commands that will be sent back. I will not show it here, but you can set the timeouts flexibly and initialize the variables from command line (e.g. argv[1]).

Here is a sample ssh_exec.exp script for password-based and authentication and privilege elevation using sudo:

#!/usr/bin/expect ## Parameters set user "username" set host "server.corporation.com" set password "Password123" set command "cat /etc/shadow" ## Commands spawn ssh -o StrictHostKeyChecking=no $user@$host expect "password:" expect "\$ " expect "password" expect "\# " temp_file 2>temp_file_error; chown $user temp_file; chown $user temp_file_error;\r"> expect "\# " expect "\$ "

Here I want to connect to server.corporation.com using credentials username/Password123 . When the scripts connects to server, server asks for password. The script expects the line with “ password: ” and sends the password value. Note the option “ -o StrictHostKeyChecking=no ” that helps to avoid checking host key against known_hosts file and related questions.

Читайте также:  Ubuntu подключить сетевой диск linux

On the host I want to read /etc/shadow file. But I can’t do it with the rights of a normal user, root access is required. So, in the same manner script expects the line with “ $ “, sends “ sudo su ” and repeats the password to elevate privileges.

Then the script expects the line with “ # ” and executes the necessary command. The output of the “ cat /etc/shadow ” will be saved in “ temp_file ” and the possible errors will be saved in “ temp_file_error “. It is also necessary to change permissions on the files, so it will be easier to get them from the server.

$ expect ssh_exec.exp spawn ssh -o StrictHostKeyChecking=no username@server.corporation.com username@server.corporation.com's password: Last login: Fri Sep 9 19:40:23 2018 from desktop12.corporation.com [username@server.corporation.com ~]$ sudo su [sudo] password for username: [root@server.corporation.com username]# cat /etc/passwd >temp_file 2>temp_file_error; chown username temp_file; chown username temp_file_error; [root@server.corporation.com username]# exit; exit

Here is a script for retrieving files from the server with password authentication. It works similar, but with scp tool:

#!/usr/bin/expect ## Parameters set user "username" set host "server.corporation.com" set password "Password123" set remotefilepath "~/temp_file" set localfilepath "temp_file" ## Commands spawn scp -o StrictHostKeyChecking=no $user@$host:$remotefilepath $localfilepath expect "password:" expect "\$ "
$ expect scp_get_file.exp spawn scp -o StrictHostKeyChecking=no username@server.corporation.com:~/temp_file temp_file username@server.corporation.com's password: temp_file 100% 2390 203.9KB/s 00:00 

In the same manner you can get the temp_file_error file.

Hi! My name is Alexander and I am a Vulnerability Management specialist. You can read more about me here. Currently, the best way to follow me is my Telegram channel @avleonovcom. I update it more often than this site. If you haven’t used Telegram yet, give it a try. It’s great. You can discuss my posts or ask questions at @avleonovchat.

Читайте также:  Перезагрузить файловую систему linux

А всех русскоязычных я приглашаю в ещё один телеграмм канал @avleonovrus, первым делом теперь пишу туда.

Источник

Оцените статью
Adblock
detector