Reading from txt file and executing an os command - python

What i want to achieve would be reading the IP/Domain from the TXT file and executing an OS import command then adding the IP/Domain when pinging.
However the problem is that for some reason it's placing a period at the end of the IP/Domain that it read from the TXT file, resulting in an invalid request when pining (the code works the only problem would be the period at the end)
for example: when the pinging line executes on the compiler it's telling me "bad parameters google.com." however on the txt file it self there is only one period which is the one for the .com it self.
def scanlist():
ipopen = open("IPlist.txt")
#Opens the IPlist.txt file and strips each of the lines so that we can read individually.
with open("IPlist.txt", "r+") as ips_file:
ips = [ip.strip() for ip in ips_file.readlines()]
#Read each line from the IPlist.txt file
with open("IPlist.txt", "r") as available_ips_file:
for ip in ips:
#Pings each line from the IPlist.txt file
response = os.system('ping -a 1 {}'.format(ip))
if response == 0: # 512/DOWN value - 0/UP value
# Up
print("- Ip Address:", ip, 'is up!')
elif response == 512:
#down
print("- IP Address:", ip, 'is down!')
else:
#other error
print("- Bad parameters or other error!")
For the entire code visit the github: https://github.com/Hontiris1/IPPing/blob/master/Ping.py

the issue was in the paramter you were passing to the ping the 1 after -a is not a valid parameter
import os
def scanlist():
#Opens the IPlist.txt file and strips each of the lines so that we can read individually.
with open("IPlist.txt") as ips_file:
ips = list(map(str.strip,ips_file.readlines()))
#Read each line from the IPlist.txt file
for ip in ips:
#Pings each line from the IPlist.txt file
response = os.system('ping {} -a -n 1'.format(ip)) # to send only one request
if response == 0: # 512/DOWN value - 0/UP value
# Up
print("- Ip Address:", ip, 'is up!')
elif response == 1: # if it's time out
#down
print("- IP Address:", ip, 'is down!')
else:
#other error
print("- Bad parameters or other error!")
scanlist()
output
Pinging 8.8.8.8 with 32 bytes of data:
Reply from 8.8.8.8: bytes=32 time=55ms TTL=56
Ping statistics for 8.8.8.8:
Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 55ms, Maximum = 55ms, Average = 55ms
- Ip Address: 8.8.8.8 is up!
Pinging stackoverflowll.com [218.93.250.18] with 32 bytes of data:
Request timed out.
Ping statistics for 218.93.250.18:
Packets: Sent = 1, Received = 0, Lost = 1 (100% loss),
- IP Address: stackoverflowll.com is down!

Related

Why am I getting "invalid input detected" for this tn.write("ip address 1.1.1.1 255.255.255.255") line?

So this script is meant to telnet into a router and change the IP address on the given interface. However, my script runs into errors and I'm not sure why. The line that errors out is line 44.
This is my python script:
import os
import sys
import telnetlib
if (len(sys.argv) != 3):
print "syntax: python hw06.py <device> <newip>"
sys.exit()
router = sys.argv[1]
newip = sys.argv[2]
interface = "Serial0/0" # must hard code the interface to avoid disaster
TIMEOUT = 3
password1 = "user"
password2 = "cisco"
cmd = "ip address 111.11.111.11 255.255.255.0"
# 1. create a telnet object
tn = telnetlib.Telnet(router, timeout=TIMEOUT)
# 2. login/telnet to the router
tn.read_until("Password: ", TIMEOUT)
tn.write(password1 + "\n")
# 3. enter into the privilege mode
tn.write("enable\n")
tn.read_until("Password:")
tn.write(password2 + "\n")
# 4. enter into the configuration mode
tn.write("configure terminal\n")
tn.read_until("(config)#", TIMEOUT)
# 5. enter into the interface configuration mode
tn.write("int" + interface + "\n")
tn.read_until("(config-if)#", TIMEOUT)
# 6. set the new IP address
tn.write(cmd + "\r\n")
# 7. exit
# exit from the interface configruaiton mode
tn.write("exit\n")
# exit from the configuraiotn mode
tn.write("exit\n")
# exit from the privilege mode
tn.write("exit\n")
print tn.read_all() # this line is required, but not sure why?
tn.close()
oid = ".1.3.6.1.2.1.4.20.1.1"
snmp = "snmpwalk -v2c -c public %s %s" % (router, oid)
# Verify the output via SNMP
fp = os.popen( snmp )
snmp = fp.read().splitlines() # split the outout into a list of "lines"
flag = 0
for line in snmp:
inline = line.rstrip('\n')
list = inline.split()
ip = list[3] # IP address is the 4th item on the list
if ip == newip:
print "The new IP address (%s) is successfully configured on Serial0/0 of %s" % (ip, router)
flag = 1
break
if flag == 0:
print "failed operation: %s is not configured on Serial0/0 of %s" % (newip, router)
Now when I run the script, i input "python script.py deviceIPaddress newInterfaceIPaddress" this is what i get:
ip address 111.11.111.11 255.255.255.0
^
% Invalid input detected at '^' marker.
Router4(config)#exit
Router4#exit
failed operation: 111.11.111.11 is not configured on Serial0/0 of <device>
Any idea why I'm getting that invalid input error?
Thank you in advanced!

Prune file size sent from server socket

I am connecting to a pre-configured server that serves four different file formats with different sizes. Each file is appended with the file size...
Example: lighthouse.jpg
561276ÿØÿà JFIF ` ` ÿî Adobe
The "561276" is the file size and needs to be pruned before saving the file.
Example: randomText.txt
45711111111111111111111111111111111111111111111111111111111
222222222222222222222222222222222222222222222222222222222
33333333333333333333333333333333333333333333333333
44444444444444444444444444444444444444444444444444444444
66666666666666666666
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
cvccccccccccccccccccccccccccccccccccccccccccccccc
ddddddddddddddddddddddddddddddddddddddddddddddddddd
The "457" is the file size and needs to be pruned before saving the file.
Some files have a size that is only 3-digits long. Some have a file size that is 6-digits long (as seen here). I want to make my code size-agnostic; regardless of how many digits is in the size.
I've tried using:
while len(buf) < 4:
buf += sock.recv(4 - len(buf))
size = struct.unpack('!i', buf)
but this only prunes the first four digits.
AND
I've tried using
len = sock.recv(4)
data = sock.recv(len)
but once again... only prunes the first four digits
Here is what I have so far:
def get_size():
buf = ''
while len(buf) < 4:
buf += sock.recv(4 - len(buf))
size = struct.unpack('!i', buf)
print "[*] Receiving %s bytes" % size
def download_pic():
size = get_size()
fname = 'tst.jpg'
with open(fname, 'wb') as img:
while True:
data = sock.recv(1024)
if not data:
break
img.write(data)
print '[*] {0} received!'.format(fname)
def main():
doconnectionstuffandprinttoconsole() #establishes connection
answer = input("[>] Your Selection: ")
sock.send(str(answer))
if answer == 2:
download_pic()
sock.close()
Any help in pruning the size from the file(s) would be greatly appreciated!
Jason Harper's suggestion (#jasonharper) got me thinking. When I ran repr(data) on the chunks from randomText.txt, I saw that it had a break in it that looked like...
'457''1111111111111111111111...
The server was attempting to send two different chunks (one at at time) but it kept getting merged into one chunk. So, I increased my sock.recv(64) up to sock.recv(256). And for some reason, it send two chunks!
'457'
'111111111...' [truncated]
NEW AND IMPROVED CODE!
import socket
import sys
import struct
import os
user1 = {'user1': 91827364}
user2 = {'user2': 19283746}
user3 = {'user3': 46372819}
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('127.0.0.1', 2058))
def print_data():
data_rcv = sock.recv(1024)
print "[-] {0}".format(data_rcv)
def download_file(format):
fname = 'download'
fullname = fname + '.' + format
try:
with open(fullname, 'wb') as txt:
len = sock.recv(256)
while True:
data = sock.recv(int(len))
if not data:
break
txt.write(data)
print("[*] {0} successfully downloaded with a length of {1} characters!".format(fullname, len))
except Exception:
print("[!] Error receiving file. Please try again.")
def connect():
print("[*] Sending Length")
sock.send("5")
my_struct = struct.pack('5s i', 'user1', 91827364)
print("[*] Sending User1 Struct")
sock.send(my_struct)
print_data()
def main():
print_data()
connect()
print_data()
answer = input("[>] Your Selection: ")
sock.send(str(answer))
if answer == 2: # Option to download Lighthouse.jpg
download_file("jpg")
elif answer == 4: # Option to download randomText.txt
download_file("txt")
sock.close()
if __name__ == "__main__":
main()
MY OUTPUT
[-] Please enter credentials
[*] Sending Length
[*] Sending User1 Struct
[-] Authenticated
[-] Choose a file to retrieve from the following list (enter the number):
1. photo.png
2. Lighthouse.jpg
3. npp.6.8.5.Installer.exe
4. randomText.txt
[>] Your Selection: 2
[*] download.jpg successfully downloaded with a length of 561276 characters!

Python Server-Client Lottery Issue

I am have an issue regarding a python assignment I was doing and would like to ask the community for some guidance. I am to use the socket module and argparse modules only for this assignment. I have created a socketserver.py file and a socketclient.py file. The connection between the server and client is fine. Now the purpose of the assignment is that the client is to send the Lottery game type, # of tickets, and # of lines per tickets using argparse. E.g. syntax for socketclient.py would be python3 -t Lotto_Max -n 2 -l 2. The output for the ticket game, ticket type and number of lines per ticket show up correctly on the server. However, they sometimes don't show correctly on the client, and am really stuck at the moment. Here is my following code....
Server Code
```socketserver.py code```
import socket
from random import sample
def main():
host = input("Please specify an IP address for this server's socket\t")
port = int(input('Please speciy a port number above 1024 for this socket.\t'))
kulmiye = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
kulmiye.bind((host, port))
except socket.error as egeh:
print('Socket bind failed. Error Code : ' + str(egeh[0]) + ' Message ' + egeh[1])
print('Socket bind accomplished...\n')
print("Listening for an incoming connection...")
kulmiye.listen()
conn, addr = kulmiye.accept()
print('Connected with ' + addr[0] + ':' + str(addr[1]))
while True:
server_data = conn.recv(1024).decode("utf-8")
game_data = server_data.split(",")
if not server_data:
break
if game_data[0] == "Lotto_Max":
nval = int(game_data[1])
lval = int(game_data[2])
for nval in range(nval):
for i in range(lval):
numbers = sample(range(1, 50), 7)
numbers.sort()
sortedd = str(numbers)
print(sortedd)
print("--------------------")
conn.sendall(sortedd.encode("utf-8"))
#conn.sendall(bytes(str(numbers),'utf-8'))
liners = "-----------------------"
conn.sendall(liners.encode("utf-8"))
print("From Client: " + str(game_data))
conn.sendall(b'goodbye')
# server_data = input('#\t')
break
else:
conn.close()
if __name__ == '__main__':
main()
Client Code
```socketclient.py code```
import socket
import argparse
def client():
host = input("Please specify the server's IP you want to connect to\t")
port = int(input("Please specify the server's port you want to connect to\t"))
kulmiye = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
kulmiye.connect((host, port))
# client_data = input("#\t")
# while True:
# client_data = input()
# if client_data == 'quit':
# kulmiye.close()
# sys.exit()
# if len(str.encode(client_data)) > 0:
# kulmiye.sendall(str.encode(client_data))
# server_response = str(kulmiye.recv(1024), "utf-8")
# print(server_response, end = " ")
kulmiye.sendall(bytes(tvar.encode("utf-8")))
kulmiye.sendall(bytes(','.encode("utf-8")))
kulmiye.sendall(bytes(str(nval).encode("utf-8")))
kulmiye.sendall(bytes(','.encode("utf-8")))
kulmiye.sendall(bytes(str(lval).encode("utf-8")))
server_data = kulmiye.recv(1024).decode("utf-8")
while server_data != 'goodbye':
server_data = kulmiye.recv(1024).decode("utf-8")
print('Server: \n' + server_data)
# client_data = input("#\t")
if not server_data:
break
kulmiye.close()
# this code block serves to give the user the ability to play lotto max
# with the amount of tickets and lines per ticket they would like
# Using the argparse module to allow the user to input command-line interfaces
parser = argparse.ArgumentParser(description='Welcome to OLG Gaming.')
parser.add_argument(
'-t',
type=str,
help="Pick the lottery you want to play",
required=True)
parser.add_argument(
'-n',
type=int,
help="Pick the amount of lottery tickets you want to play",
required=True)
parser.add_argument(
'-l',
type=int,
help="Pick the amount of lines you would like to play",
required=True)
# parser.add_argument('-o', type = str, help = "This is optional", required = False)
# parse_args will convert the argument strings into objects and will get
# stored in the cmdargs variable
cmdargs = parser.parse_args()
tvar = cmdargs.t # the t string argument that gets parsed into an object will get stored into a variable called tvar
# the n integer argument that gets parsed into an object will get stored
# into a variable called nval
nval = int(cmdargs.n)
# the l integer argument that gets parsed into an object will get stored
# into a variable called lval
lval = int(cmdargs.l)
if __name__ == "__main__":
client()
```code```
Server
python3 socketserver.py
specify localhost as IP
specify a port e.g. 4444
Client
python3 socketclient.py -t Lotto_Max -n 1 -l 1
specify an IP address to connect to the server (e.g. localhost or 127.0.0.1)
specify a port to connect to e.g. 4444
When the connection establishes between client and server, the server receives the client input and prints it on its end the gametype (Lotto_Max), number of tickets and lines per ticket
Server will output the resultse.g.
However, the client won't receive it indefinitely. Usually it'll get it about 25% of the time, and I am not sure why
One problem is here in the server:
server_data = conn.recv(1024).decode("utf-8")
conn.recv(1024) can receive any number of bytes from 0 (closed connection) to 1024. The line above assumes the whole message is received every time, but when it fails it only gets part of the message. Below I've modified your code so the server can process multiple client connections one at a time, and the client will connect/disconnect over and over again to hasten the failure:
Server:
import socket
from random import sample
def main():
host = ''
port = 4444
kulmiye = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
kulmiye.bind((host, port))
print('Socket bind accomplished...\n')
print("Listening for an incoming connection...")
kulmiye.listen()
while True:
conn, addr = kulmiye.accept()
print('Connected with ' + addr[0] + ':' + str(addr[1]))
with conn:
server_data = conn.recv(1024).decode("utf-8")
print(f'server_data={server_data}')
game_data = server_data.split(",")
print("From Client: " + str(game_data))
if server_data:
if game_data[0] == "Lotto_Max":
nval = int(game_data[1])
lval = int(game_data[2])
for nval in range(nval):
for i in range(lval):
numbers = sample(range(1, 50), 7)
numbers.sort()
sortedd = str(numbers)
print(sortedd)
print("--------------------")
conn.sendall(sortedd.encode("utf-8"))
liners = "-----------------------"
conn.sendall(liners.encode("utf-8"))
conn.sendall(b'goodbye')
if __name__ == '__main__':
main()
Client:
import socket
import argparse
def client():
host = 'localhost'
port = 4444
kulmiye = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
kulmiye.connect((host, port))
kulmiye.sendall(bytes(tvar.encode("utf-8")))
kulmiye.sendall(bytes(','.encode("utf-8")))
kulmiye.sendall(bytes(str(nval).encode("utf-8")))
kulmiye.sendall(bytes(','.encode("utf-8")))
kulmiye.sendall(bytes(str(lval).encode("utf-8")))
server_data = kulmiye.recv(1024).decode("utf-8")
while server_data != 'goodbye':
server_data = kulmiye.recv(1024).decode("utf-8")
print('Server: \n' + server_data)
# client_data = input("#\t")
if not server_data:
break
kulmiye.close()
tvar = 'Lotto_Max'
nval = 1
lval = 1
if __name__ == "__main__":
while True:
client()
Here's the result after 100s of successful connections. Note server_data between the successful and unsuccessful connection:
Connected with 127.0.0.1:12175
server_data=Lotto_Max,1,1
From Client: ['Lotto_Max', '1', '1']
[4, 7, 9, 12, 24, 31, 48]
--------------------
Connected with 127.0.0.1:12176
server_data=Lotto_Max,1,
From Client: ['Lotto_Max', '1', '']
Traceback (most recent call last):
File "C:\server.py", line 38, in <module>
main()
File "C:\server.py", line 24, in main
lval = int(game_data[2])
ValueError: invalid literal for int() with base 10: ''
conn.recv(1024) didn't receive the complete message (didn't get the final 1). TCP is a byte streaming protocol with no concept of message boundaries. You're code is responsible to call recv() and buffer the data until you have a complete message. You could send fixed-sized messages and call recv until you have that many bytes, terminate a message with a sentinel byte such as a newline(\n) and read until the sentinel is received, or send the size of the message first followed by the message bytes.
I won't solve it for you since it is an assignment, but as a hint socket.makefile can wrap the socket in a file-like object where you can call .read(n) to read exactly n bytes from a socket, or .readline() to read a \n-terminated line.
Here's a link to an answer of mine that demonstrates this: https://stackoverflow.com/a/55840026/235698
Another example of the streaming nature of TCP is on the client side. Sometimes, it prints:
-----------------------
Server:
goodbye
Server:
-----------------------goodbye
Server:
Server:
-----------------------
Server:
goodbye
The separate lines in the server:
conn.sendall(liners.encode("utf-8"))
conn.sendall(b'goodbye')
Sometimes get received by the single recv in the client:
server_data = kulmiye.recv(1024).decode("utf-8")
Again, this is due to the streaming nature of TCP and no message boundaries. If you sent each line terminated by a newline, you could call recv() a number of times until a newline was detected, then process just that line.
Another answer that illustrates this technique is here: https://stackoverflow.com/a/55186805/235698.
Thank you Mark Tolonen for your guidance. I still need to brush up how to handle TCP data stream. Nevertheless, I was able to achieve more desirable results using numerous
conn.sendall within my nested for loop. Happy camper!

XOR decryption not working when used in script

I've been working on an assignment but have hit the wall at the last steps now.
The task is to automate process of connecting to server, receiving reply, processing the reply - decrypt it, encode and send it back to server.
Here is the main script, i know the data receiving part is not really proper way of doing it but it works for this task:
# -*- encoding: utf-8 -*-
import socket, sys, time
from decryptmsg import decryptmsg
from cleanmsg import cleanmsg
from getkey import getkey
from xor import xorstring
#connection
ip=<ipaddress>
port=<port>
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((ip,port))
while True:
print "[+] START COMMUNICATION WITH SERVER..."
data = sock.recv(8192)
if not data:
print "[-] ei dataa"
print "[+] RECEIVED DATA: " + data
data = cleanmsg(data)
key = str(getkey(data))
print "[+] GOT KEY: " + key
if data != None:
print "[!] PROCESSING DATA: " + data
clear_text = xorstring(data, key, decode=True)
print clear_text
if clear_text == None:
print "[-] NO RESULTS FROM DECRYPTION"
break
else:
print "[+] DECRYPTION SUCCESFULL, SENDING MESSAGE..."
sock.sendall(clear_text)
sock.sendall("\n")
continue
Here are also the function modules:
cleanmsg.py
import re
b64pattern = '(?:[A-Za-z0-9+/]{4}){2,}(?:[A-Za-z0-9+/]{2}[AEIMQUYcgkosw048]=|[A-Za-z0-9+/][AQgw]+={0,2})'
def cleanmsg(data):
if re.search(b64pattern, data):
b64data = re.search(b64pattern,data).group(0).strip()
return b64data
getkey.py
# -*- encoding: utf-8 -*-
import sys, base64, subprocess, os
def getkey(cleaned_data):
key = ""
with open("secret_key.txt", 'w') as file:
try:
file.write(base64.b64decode(cleaned_data + b'==='))
except:
print "[-] B64 DECODE FAILED: "
cmd = 'xortool -m 64 -c 20 secret_key.txt'
process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output = process.stdout.read()
lines = iter(output.splitlines())
for line in lines:
#to see output of xortool
print "[+]" + line
if "possible" in line:
key = next(lines, '')
print "[!] POSSIBLE KEY DETECTED BY XORTOOL: " + key
return key
xor.py
def xorstring(data, key="v", encode=False, decode=False):
from itertools import izip, cycle
import base64
if decode:
data = str(data)
data = base64.b64decode(data + b'===')
xored = ''.join(chr(ord(x) ^ ord(y)) for (x,y) in izip(data, cycle(key)))
if encode:
return base64.encodestring(xored).strip()
return xored
Output from this is following:
[+] START COMMUNICATION WITH SERVER...
[+] RECEIVED DATA: he7Jw8LCw4uH3sjS1YfC38bK18vCh87Uh8bJh9LJwcjV09LJxtPCh8jJwofByNWH3sjS1YfG1cDSysLJ04uFrdTGzsOH78jLysLUi4fTxszOycCH08/Ch9fG18LVh8bJw4fAy8bJxM7JwIfPztSHwt7Ch8PI0MmHztOJh4Xzz87Urc7Uh9PPwofj0snDxtSH1MLXxtXG087IyYfExtTCi4fGycOLh8bUh87Th8/G19fCydSLh+6H0MbUh8LJwMbAwsOtzsmHxMvCxtXOycCH0teH1MjKwofUysbLy4fXyM7J09SHzsmHxMjJycLE087IyYfQztPPh87TiYfzz8Ktz9LUxcbJw4fQxtSHxofTwsLTyNPGy8LVi4fTz8LVwofQxtSHyciHyNPPwtWH0MjKxsmLh8bJw4fTz8KtxMjJw9LE04fEyMrXy8bOycLDh8jBh9DG1IfTz8bTh8/Ch8/Gw4fD1c7B08LDh87J08iH08/Ch8/Gxc7Th8jBrdDOycPOycCH0teHwtHC1d6HysLGy4fF3ofTxszOycCHyNLTh8/O1IfBxsvUwofTwsLTz4fGycOHz9LVy87JwK3Tz8LKh8bTh8/O1IfQzsHCi4fQz87Ez4uH3sjSh9DOy8uHxsvLyNCLh87Uh8nI04fGyYfGxNPOyMmHy87MwsverdPIh8jExNLVh9PIh9PPwofOysbAzsnG087IyYfIwYfTz8KHxtHC1cbAwofU08jV3orTwsvLwtWJh/PGzMKHxq3XzsnEz4fIwYfUydLBwYuH48jE08jVi4fGycOHxsTMycjQy8LDwMKH08/G04fuh8/G0cKH1MTI1cLDh8jRwtWt3sjSh87Jh97I0tWHwt/GytfLwomFkZaWn5SRkZ+XkZWSlZ+Qkp6SlJI=
Enter the SHA-256 hash of the plaintext (in hex):
[+]The most probable key lengths:
[+] 1: 23.3%
[+] 6: 19.4%
[+] 12: 14.2%
[+] 17: 11.0%
[+] 20: 9.8%
[+] 35: 5.4%
[+] 40: 4.6%
[+] 42: 4.7%
[+] 46: 3.9%
[+] 48: 3.6%
[+]Key-length can be 3*n
[+]Key-length can be 4*n
[+]1 possible key(s) of length 1:
[!] POSSIBLE KEY DETECTED BY XORTOOL: \xa7
[+]Found 1 plaintexts with 95.0%+ printable characters
[+]See files filename-key.csv, filename-char_used-perc_printable.csv
[+] GOT KEY: \xa7
[!] PROCESSING DATA: he7Jw8LCw4uH3sjS1YfC38bK18vCh87Uh8bJh9LJwcjV09LJxtPCh8jJwofByNWH3sjS1YfG1cDSysLJ04uFrdTGzsOH78jLysLUi4fTxszOycCH08/Ch9fG18LVh8bJw4fAy8bJxM7JwIfPztSHwt7Ch8PI0MmHztOJh4Xzz87Urc7Uh9PPwofj0snDxtSH1MLXxtXG087IyYfExtTCi4fGycOLh8bUh87Th8/G19fCydSLh+6H0MbUh8LJwMbAwsOtzsmHxMvCxtXOycCH0teH1MjKwofUysbLy4fXyM7J09SHzsmHxMjJycLE087IyYfQztPPh87TiYfzz8Ktz9LUxcbJw4fQxtSHxofTwsLTyNPGy8LVi4fTz8LVwofQxtSHyciHyNPPwtWH0MjKxsmLh8bJw4fTz8KtxMjJw9LE04fEyMrXy8bOycLDh8jBh9DG1IfTz8bTh8/Ch8/Gw4fD1c7B08LDh87J08iH08/Ch8/Gxc7Th8jBrdDOycPOycCH0teHwtHC1d6HysLGy4fF3ofTxszOycCHyNLTh8/O1IfBxsvUwofTwsLTz4fGycOHz9LVy87JwK3Tz8LKh8bTh8/O1IfQzsHCi4fQz87Ez4uH3sjSh9DOy8uHxsvLyNCLh87Uh8nI04fGyYfGxNPOyMmHy87MwsverdPIh8jExNLVh9PIh9PPwofOysbAzsnG087IyYfIwYfTz8KHxtHC1cbAwofU08jV3orTwsvLwtWJh/PGzMKHxq3XzsnEz4fIwYfUydLBwYuH48jE08jVi4fGycOHxsTMycjQy8LDwMKH08/G04fuh8/G0cKH1MTI1cLDh8jRwtWt3sjSh87Jh97I0tWHwt/GytfLwomFkZaWn5SRkZ+XkZWSlZ+Qkp6SlJI=
��������ꂰ�✙��ь����綫����ړ��ɒ�������۹�✅���������������ϝ����������ꏾ��қ��ԙ������ꚱ��ې��ߕ������Ꞧ��ؓज�㲶�����կ㜈��������綹����݈���������������ݏ���������������˝��ْ����𜣕���ٝ��қ�����������ݐ��̓�������ۼ��ҙ��Փ������꒫������ԉ����𶽚�������ȓ������ꏷ�������������������ѝ�朝�����������ɟ��ߓ�����������������������꓾��؎��ș������ꏷ��ԝ���������������Ɍ��ʙ�������۽��ȝ��қ�����������Џ��ș�������۷��Е����������ꓶ��˕����������ꂰ��˕�������븶������������������������㥜��������۫������ە������ꔹ��ԙ��ʙ�����徔���ș��َ��������ն�ҟ��Ӛ�������ۛ��ȓ�朝�����������؛��Ȕ���մ������ߓ���������漏���������������������Ĥ��ħ�����������
[+] DECRYPTION SUCCESFULL, SENDING MESSAGE...
[+] START COMMUNICATION WITH SERVER...
Traceback (most recent call last):
File "challenge.py", line 19, in <module>
data = sock.recv(8192)
socket.error: [Errno 104] Connection reset by peer
So the data is not properly decrypted.
However, if i take the output from above and insert it to the test script below:
# -*- encoding: utf-8 -*-
import sys
from xor import xorstring
key = '\xa7'
string = 'he7Jw8LCw4uH3sjS1YfC38bK18vCh87Uh8bJh9LJwcjV09LJxtPCh8jJwofByNWH3sjS1YfG1cDSysLJ04uFrdTGzsOH78jLysLUi4fTxszOycCH08/Ch9fG18LVh8bJw4fAy8bJxM7JwIfPztSHwt7Ch8PI0MmHztOJh4Xzz$
dekoodattu = xorstring(string, key, decode=True)
print dekoodattu
and run the script, the output is correct:
root#45s:~# python test.py
"Indeed, your example is an unfortunate one for your argument,"
said Holmes, taking the paper and glancing his eye down it. "This
is the Dundas separation case, and, as it happens, I was engaged
in clearing up some small points in connection with it. The
husband was a teetotaler, there was no other woman, and the
conduct complained of was that he had drifted into the habit of
winding up every meal by taking out his false teeth and hurling
them at his wife, which, you will allow, is not an action likely
to occur to the imagination of the average story-teller. Take a
pinch of snuff, Doctor, and acknowledge that I have scored over
you in your example."61183668062528759535
I'm totally lost here that why is the script working on it's own but in the main script the decryption is mangled - i guess something is added or removed from either the key or string in some stage but can't figure out where or why.
Any help is extremely appreciated :)

Retrieving response from network and print with Python

I have a problem.
I've written this part of code in Python (Tornado web server):
if command == 'RESTARTNWK':
op_group = "A3"
op_code = "E0"
netid = hextransform(int(nid), 16)
packet_meta = "*%s;%s;%s;#"
pkt_len = hextransform(0, 2)
packet = packet_meta % (op_group, op_code, pkt_len)
packet = packet.upper()
op_group_hex=0xA3
op_code_hex=0xE0
cmdjson = packet2json(op_group_hex,op_code_hex, packet)
mynet_type="ztc"
print("\t\t " + packet + "\n")
#TODO : -write command into db
ts = datetime.datetime.now().isoformat()
mynet_type ="ztc"
self.lock_tables("write", ['confcommands'])
self.db.execute("INSERT INTO confcommands (network_id, ntype, timestamp, command) \
VALUES (%s,%s,%s,%s)", nid, mynet_type, ts, cmdjson)
self.unlock_tables();
# TODO: - open the /tmp/iztc file in append mode
cmdfile = open('/tmp/iztc', 'a')
# - acquire a lock "only for the DB case, it's easier"
# - write the packet
cmdfile.write(netid + "\t"+ mynet_type + "\t"+ ts + "\t"+ cmdjson +"\n");
# - release the lock "only for the DB case, it's easier"
# - close the file
cmdfile.close()
if command == 'RESTARTNWK':
opcodegroupr = "A4"
opcoder = "E0"
#Code for retrieving the MAC address of the node
como_url = "".join(['http://', options.como_address, ':', options.como_port,
'/', ztc_config, '?netid=', netid,
'&opcode_group=', opcodegroupr,
'&opcode=', opcoder, '&start=-5m&end=-1s'])
http_client = AsyncHTTPClient()
response = yield tornado.gen.Task(http_client.fetch, como_url)
ret = {}
if response.error:
ret['error'] = 'Error while retrieving unregistered sensors'
else:
for line in response.body.split("\n"):
if line != "":
value = int(line.split(" ")[6])
ret['response'] = value
self.write(tornado.escape.json_encode(ret))
self.finish()
In this code I receive the restart network command from the user. After some settings, I write the relative command in a db table named confcommands. The server will read this command and will send to the specified network the restart signal.
After this, if all it's ok, the network resend me the response. I read this response with a http request to my server (como), and wait for the asynchronous response.
Where the response is written by the network, I have to find this in the packet. The value response is the sixth element. Other information of the packet are the opgroup and opcode, the network from which is the response, and other informations.
Then I write the response for the user.
I don't know if this code is right... can work this? The structure seems to me right....
Thank you all for any suggestions!

Categories

Resources