예제 #1
0
 def install_tor(self):
     self.connection()
     if not self.alive:
         return
     print('Installing Tor ...')
     shell('echo "deb http://http.kali.org/kali kali-rolling main contrib non-free" > /etc/apt/sources.list \
                                 && apt-get update && apt-get install tor -y && apt autoremove -y')
예제 #2
0
def main():
    output = shell(["netsh", "wlan", "show",
                    "profiles"]).decode("ansi").split("\n")
    wifis = [
        line.split(":")[1][1:-1] for line in output
        if ("Profil Tous les utilisateurs" in line)
    ]

    print("\n Wifi stored:\n ---- ------\n")

    for wifi in wifis:
        output = shell(
            ["netsh", "wlan", "show", "profiles", wifi,
             "key=clear"]).decode("ansi").split("\n")
        password = [
            line.split(":")[1][1:-1] for line in output
            if ("Contenu de la cl" in line)
        ]

        try:
            print(f"  {wifi}{' '*(30-len(wifi))}: {password[0]}")

        except Exception:
            print(f"  {wifi}{' '*(30-len(wifi))}: -")

    return (True)
예제 #3
0
    def getNewIP(self, recurrence):
        if not self.alive:
            self.exit()

        try:
            ip = self.getIP()
            if all([not ip, recurrence]):
                print(
                    "Network unreachable! Trying Again by restarting network manager"
                )
                retry = 2
                while (retry):
                    ip = self.getIP()
                    if ip:
                        break
                    else:
                        shell('service network-manager restart')
                        sleep(1)
                if not ip:
                    self.getNewTorIP(recurrence - 1)
            # If IP still not available and recurrence has exhausted, then first check internet connection
            if all([not self.ip, not recurrence]):
                self.connection()
            if ip not in self.recentIPs:
                self.ip = ip
                self.recentIPs.append(ip)
            else:
                print("Same IP detected restarting tor")
                self.getNewTorIP()
        except Exception as e:
            print(e)
예제 #4
0
    def updateIp(self, recur=3):
        if not self.alive: self.exit()
        socks.socket.setdefaulttimeout(5)
        socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, '127.0.0.1', 9050, True)
        socket.socket = socks.socksocket

        try:
            ip = self.getIp()
            if all([not ip, recur]):
                print('Error: Network unreachable')
                reset_counts = 2
                for _ in range(30):
                    if not self.alive: return
                    ip = self.getIp()
                    if ip: break
                    else:
                        if reset_counts:
                            reset_counts -= 1
                            shell('service network-manager restart')
                        sleep(1)
                if not ip: self.restartTor(recur - 1)
            if all([not ip, not recur]): self.connection()

            if ip in self.recentIPs.queue: self.restartTor()
            else:
                self.ip = ip
                self.recentIPs.put(ip)

        except:
            pass
def get_en_audio(word):
    url = 'https://media-audio1.baydn.com/us/'
    url += word[0] + '/' + word[0:2] + '/' + word + '_v3.mp3'
    try:
        request.urlretrieve(url, 'en.mp3')
        shell(
            'avconv -i en.mp3 -f mp3 -ab 128k -ar 44100 -ac 2 -y -v quiet _en.mp3',
            shell=True)
        return 1
    except:
        return 0
def get_cn_audio(word):
    url = 'http://fanyi.baidu.com/gettts?lan=zh&text='
    url += urllib.parse.quote(word) + '&spd=5&source=web'
    try:
        request.urlretrieve(url, 'cn.mp3')
        shell(
            'avconv -i cn.mp3 -f mp3 -ab 128k -ar 44100 -ac 2 -y -v quiet _cn.mp3',
            shell=True)
        return 1
    except:
        return 0
예제 #7
0
def x(cmd):
    # imports
    from psutil import MACOS, WINDOWS, LINUX
    from subprocess import Popen as shell
    from sys import stdout
    # shell cfg
    if WINDOWS:
        SHELL, NEXT_CMD = "powershell", ";"
    elif MACOS or LINUX:
        SHELL, NEXT_CMD = "sh", ";"
    # run
    shell([SHELL, NEXT_CMD.join(cmd)], stdout=stdout).communicate()
def get_audio(word, filename):
    has_en, has_cn = 1, 1
    word_en = word[0]
    word_cn = word[1].split('.')[-1].replace('...', '什么什么')
    has_en = get_en_audio(word_en)
    has_cn = get_cn_audio(word_cn)
    time.sleep(3)
    if has_en and has_cn:
        shell("cat _en.mp3 _cn.mp3 blank.mp3 >> _" + filename + ".mp3",
              shell=True)
        # shell("cat _en.mp3 blank.mp3 >> _" + filename + ".mp3", shell=True)
        return 1
    else:
        return 0
def pass_the_hash(domain, ip, user_name, lm_hash, ntlm_hash, command, timeout):
    try:
        logging.debug(
            'ATTEMPT - {domain}{user_name}%{lm_hash}:{ntlm_hash}//{ip} - {command}'
            .format(domain=domain,
                    user_name=user_name,
                    lm_hash=lm_hash,
                    ntlm_hash=ntlm_hash,
                    ip=ip,
                    command=command))
        result = shell([
            'pth-winexe', '-U',
            domain + user_name + '%' + '{lm_hash}:{ntlm_hash}'.format(
                lm_hash=lm_hash, ntlm_hash=ntlm_hash), '//' + ip, command
        ],
                       stderr=open(os.devnull, 'w'),
                       timeout=timeout)
        logging.info(
            '{domain}{user_name}%{lm_hash}:{ntlm_hash}//{ip} - {result}'.
            format(domain=domain,
                   user_name=user_name,
                   lm_hash=lm_hash,
                   ntlm_hash=ntlm_hash,
                   ip=ip,
                   result=result))
    except Exception as e:
        logging.debug(
            "{domain}{user_name}%{lm_hash}:{ntlm_hash}//{ip} - {error}".format(
                domain=domain,
                user_name=user_name,
                lm_hash=lm_hash,
                ntlm_hash=ntlm_hash,
                ip=ip,
                error=e))
예제 #10
0
 def get_commit(self, sha, path):
     try:
         return shell(["git", "show", sha],
                      cwd=os.path.dirname(os.path.realpath(path)),
                      startupinfo=si)
     except Exception as e:
         return
예제 #11
0
def spawn_new_standard_repo(target_name, subdir_name):
    """ spawn_new_standard_repo """
    shell(f"cp -r colab-env {target_name}", shell=True)
    shell(f"cp -r colab-env/.* {target_name}", shell=True)
    shell(f"mv {target_name}/colab_env {target_name}/{subdir_name}",
          shell=True)
    shell(
        f"mv {target_name}/k8s/live/colab-env.cron.yaml {target_name}/k8s/live/{target_name}.cron.yaml",
        shell=True)
예제 #12
0
 def checkTorIsUp(self):
     if shell(
             'curl --socks5 localhost:9050 --socks5-hostname localhost:9050 -s https://check.torproject.org/ | cat | grep -m 1 Congratulations | xargs'
     ).startswith('Congratulations'):
         print("Tor is running")
         return True
     else:
         print('Tor restart failed')
         return False
예제 #13
0
 def get_blame(self, line, path):
     try:
         return shell([
             "git", "blame", "--minimal", "-w", "-L {0},{0}".format(line),
             path
         ],
                      cwd=os.path.dirname(os.path.realpath(path)),
                      startupinfo=si)
     except Exception as e:
         return
예제 #14
0
 def get_blame(self, line, path):
     try:
         return shell(["git", "blame", "--minimal", "-w",
             "-L {0},{0}".format(line), path],
             cwd=os.path.dirname(os.path.realpath(path)),
             startupinfo=si,
             stderr=subprocess.STDOUT)
     except subprocess.CalledProcessError as e:
         print("Git blame: git error {}:\n{}".format(e.returncode, e.output.decode("UTF-8")))
     except Exception as e:
         print("Git blame: Unexpected error:", e)
예제 #15
0
	def make_thumb(self, infile, outfile, size):
		command = "aapt d --values badging %s" % infile
		data = [line.replace("'", "").split(":") for line in shell(command.split()).splitlines()]
		icons = [item for item in data if item[0].startswith("application-icon")]
		if len(icons) == 0:
			return False
		icons = sorted(icons, key = lambda item: int(item[0].split("-")[-1]), reverse = True)
		icon = icons[0][1]
		apkfile = zipfile.ZipFile(infile, mode = 'r')
		icondata = apkfile.read(icon)
		with open(outfile, 'wb') as of:
			of.write(icondata)
예제 #16
0
    def _close_server(self):
        if self.kill_when_connection_lost:
            print("kill before")
            # os.kill(os.getpgid(self.server.pid), signal.SIGKILL)
            # self.server.kill()
            print(self.out)
            subprocess.call(['docker', 'stop', self.out[:-1]])

            while True:
                cmd = shell("docker ps -q")
                if cmd == "":
                    break

            print("kill after")
            return
예제 #17
0
 def get_blame_lines(self, path):
     '''Run `git blame` and get the output lines.
     '''
     try:
         # The option --show-name is necessary to force file name display.
         command = ["git", "blame", "--show-name", "--minimal", "-w", path]
         output = shell(command,
                        cwd=os.path.dirname(os.path.realpath(path)),
                        startupinfo=si,
                        stderr=subprocess.STDOUT)
         return output.decode("UTF-8").splitlines()
     except subprocess.CalledProcessError as e:
         print("Git blame: git error {}:\n{}".format(
             e.returncode, e.output.decode("UTF-8")))
     except Exception as e:
         print("Git blame: Unexpected error:", e)
예제 #18
0
def relocation(target_path):
    """ relocation """
    target_name = target_path.split("/")[-1]
    target_loc = "/".join(target_path.split("/")[:-1])
    shell(f"mv {target_name}/* {target_path} --force", shell=True)
    shell(f"rm -r {target_name}", shell=True)
예제 #19
0
             label='coverage distribution')
    plt.xlim(0, cov['percentage_at_depth'][10:].idxmax() * 3)
    plt.title(f'{sample} - 95% of reads over {_95}-fold coverage')
    plt.legend()
    plt.xlabel('coverage depth')
    # bla.text --> bla.svg
    svg_file = csv_file.replace('txt', 'svg')
    print(f"Saving {svg_file}")
    plt.savefig(f"{svg_file}")


workdir = snakemake.config['workdir']
input = snakemake.input
output = os.path.join(workdir, str(snakemake.output))
log = snakemake.log

params = snakemake.params
exon_cover = params.exon_cover
prettifyBed = params.prettifyBed
w = snakemake.wildcards
sample_name = f"{w.sample}"

refgen = params.refgen

cmd = f"bedtools coverage -b {input.sample} -a {exon_cover} -hist -sorted -g {refgen}.genome 2>{log} | grep \'^all\' | sort -k2,2nr | {prettifyBed} | sort -k2,2n > {output}"
exit = shell(cmd, shell=True)
if exit == 0:
    get_cover_svg(output, sample_name)

shell(cmd, shell=True)
예제 #20
0
 def startTor(self):
     # Ignore error if it is already running
     shell('service tor start')
     sleep(5)
예제 #21
0
def name_replacement(f_name, target_name, subdir_name):
    """ name_replacement """
    if not os.path.isfile(f_name):
        return
    shell(f"sed -i 's/colab-env/{target_name}/g' {f_name}", shell=True)
    shell(f"sed -i 's/colab_env/{subdir_name}/g' {f_name}", shell=True)
def check_if_git_tracked(path):
    result = shell(["git", "rev-parse", "--is-inside-work-tree"],
                   cwd=os.path.dirname(os.path.realpath(path)))
    print("check_if_git_tracked", result)
    return result
예제 #23
0
 def stopTor(self):
     shell('service tor stop')
     self.alive = False
예제 #24
0
def add_short_description(target_name):
    """ add short description """
    description = input("Enter short description for repo: ")
    shell(
        f"sed -i 's/SHORT DESCRIPTION HERE/{description}/g' {target_name}/setup.py",
        shell=True)
예제 #25
0
div = "-" * 75
f = open("/app/input.txt", "r+")
tl = f.read().split("\n")
f.close()
bl = []
ul = []
count = 0
for t in tl:
    count = count + 1
    print(f"loading token {count}...")
    if " --user" not in t:
        if showtokens:
            cmd = f"python3 /app/bot.py {t}"
        else:
            cmd = f"python3 /app/bot.py {t} h"
        bl.append(procout(shell(cmd, shell=True, text=True).replace("\n", "")))
    if " --user" in t:
        t = t.replace(" --user", "")
        if showtokens:
            cmd = f"python3 /app/user.py {t}"
        else:
            cmd = f"python3 /app/user.py {t} h"
        ul.append(procout(shell(cmd, shell=True, text=True).replace("\n", "")))
print("processing data...")
d = {}
count = 0
if len(bl) > 0:
    bd = {}
    for i in bl:
        count = count + 1
        bd.update({n2w(count): i})
예제 #26
0
파일: lcd.py 프로젝트: Mezgrman/K8055
def run():
	parser = argparse.ArgumentParser()
	parser.add_argument('-m', '--mode', choices = ['stats', 'text', 'textpad', 'interactive', 'music'], default = 'interactive')
	parser.add_argument('-t', '--text', default = "Hello world!")
	parser.add_argument('-c', '--cursor', action = 'store_true')
	parser.add_argument('-cb', '--cursor-blink', action = 'store_true')
	parser.add_argument('-w', '--wrap', action = 'store_true')
	parser.add_argument('-s', '--scroll', action = 'store_true')
	parser.add_argument('-sd', '--scroll-delay', type = float, default = 0.25)
	parser.add_argument('-si', '--skip-init', action = 'store_true')
	parser.add_argument('-a', '--align', choices = ['left', 'center', 'right'], default = 'left')
	args = parser.parse_args()
	
	# k = pyk8055.k8055(0)
	k = None
	display = K80554BitLCDController(board = k, pinmap = PINMAP, charmap = CHARMAP, lines = 2, columns = 16, skip_init = args.skip_init, debug = False)
	display.set_display_enable(cursor = args.cursor, cursor_blink = args.cursor_blink)
	display.clear()
	display.home()
	
	try:
		if args.mode == 'interactive':
			key_reader = KeyReader()
			ui = K8055LCDUI(display, key_reader)
			"""ui.dim(0, animate = True, duration = 1.0)
			ui.dim(1023, animate = True, duration = 1.0)
			ui.dim(0, animate = True, duration = 1.0)
			ui.dim(1023, animate = True, duration = 1.0)
			ui.dim(800, animate = False)
			time.sleep(0.25)
			ui.dim(600, animate = False)
			time.sleep(0.25)
			ui.dim(400, animate = False)
			time.sleep(0.25)
			ui.dim(200, animate = False)
			time.sleep(0.25)
			ui.dim(0, animate = False)
			time.sleep(0.25)
			ui.dim(1023, animate = True, duration = 1.0)"""
			while True:
				res = ui.list_dialog("Welcome!", ("Textpad mode", "Clock", "System info", "Demos", "Settings", "Quit"), align = 'center')
				if res[1] == "Textpad mode":
					ui.clear()
					try:
						while True:
							char = key_reader.read_key()
							if char:
								display.write(char)
					except KeyboardInterrupt:
						pass
					ui.clear()
				elif res[1] == "Clock":
					try:
						while True:
							data = time.strftime("%a, %d.%m.%Y\n%H:%M:%S")
							ui.message(data, align = 'center')
							time.sleep(1)
					except KeyboardInterrupt:
						pass
				elif res[1] == "System info":
					while True:
						ires = ui.list_dialog("System info", ("Load average", "Disk space", "Memory", "Back"), align = 'center')
						if ires[1] == "Load average":
							try:
								while True:
									with open("/proc/loadavg", 'r') as f:
										loadavg = f.read()
									data = "* LOAD AVERAGE *\n" + "  ".join(loadavg.split()[:3])
									ui.message(data, align = 'center')
									time.sleep(5)
							except KeyboardInterrupt:
								pass
						elif ires[1] == "Disk space":
							try:
								while True:
									space = os.statvfs("/")
									free = (space.f_bavail * space.f_frsize) / 1024.0 / 1024.0
									total = (space.f_blocks * space.f_frsize) / 1024.0 / 1024.0
									data = "Total\t%.2fMB\nFree\t%.2fMB" % (total, free)
									ui.message(data)
									time.sleep(5)
							except KeyboardInterrupt:
								pass
						elif ires[1] == "Memory":
							try:
								while True:
									mem = psutil.phymem_usage()
									free = mem[2] / 1024.0 / 1024.0
									total = mem[0] / 1024.0 / 1024.0
									data = "Total\t%.2fMB\nFree\t%.2fMB" % (total, free)
									ui.message(data)
									time.sleep(5)
							except KeyboardInterrupt:
								pass
						elif ires[1] == "Back":
							break
				elif res[1] == "Demos":
					while True:
						dres = ui.list_dialog("Demos", ("Progress bar", "Input dialog", "Back"), align = 'center')
						if dres[1] == "Progress bar":
							x = 0.0
							bar = ui.progress_bar("Testing...", fraction = x, char = "*")
							while x < 1.0:
								x += 1.0 / 16.0
								bar.update(fraction = x)
							time.sleep(1.5)
							ui.message("Done :)", align = 'center')
							time.sleep(3)
						elif dres[1] == "Input dialog":
							name = ui.input_dialog("Your name?")
							ui.message("Hello %s!" % name, align = 'center')
							time.sleep(3)
						elif dres[1] == "Back":
							break
				elif res[1] == "Settings":
					while True:
						sres = ui.list_dialog("Settings", ("Brightness", "Back"), align = 'center')
						if sres[1] == "Brightness":
							count = ui.slider_dialog("Brightness", 0, 1023, step = 5, big_step = 100, value = ui.display.brightness)
							ui.dim(count)
						elif sres[1] == "Back":
							break
				elif res[1] == "Quit":
					ui.clear()
					ui.dim(0)
					break
		elif args.mode == 'music':
			while True:
				data = shell(['mocp', '--info'])
				if "FATAL_ERROR" in data:
					string = "Not running"
				else:
					metadata = [line.split(": ") for line in data.splitlines()]
					metadata = dict([(line[0], ": ".join(line[1:])) for line in metadata])
					string = "%(Artist)s\n%(Title)s" % metadata
				display.write(string, align = 'center')
				time.sleep(5)
		elif args.mode == 'textpad':
			while True:
				char = key_reader.read_key()
				if char:
					display.write(char)
		elif args.mode == 'text':
			text = args.text.replace("\\n", "\n")
			display.write(text, wrap = args.wrap, align = args.align)
			while args.scroll and len(args.text) > display.column_count:
				display.scroll()
				time.sleep(args.scroll_delay)
		elif args.mode == 'stats':
			while True:
				with open("/proc/loadavg", 'r') as f:
					loadavg = f.read()
				data = "* LOAD AVERAGE *\n" + "  ".join(loadavg.split()[:3])
				display.write(data, wrap = args.wrap, update = True, align = args.align)
				time.sleep(5)
	except KeyboardInterrupt:
		pass
	except:
		raise
	finally:
		display.shutdown()
예제 #27
0
	def lt_proc(self, type, data):
		return shell(self.cmds[type], input=data)
예제 #28
0
import sys
from subprocess import check_output as shell
command = ["docker", "node", "ls"]
nodes = shell(command).decode().split("\n")[1:]
n = len(nodes)

for i in range(n):
	nodes[i] = nodes[i].split(" ")
count = 0
if sys.argv[1]=="me":
	for i in range(n):
		if "*" in nodes[i]:
			print(nodes[i][4])
			break
else:
	for i in range(n):
		if "*" not in nodes[i]:
			count+=1
			if str(count)==sys.argv[1]:
				print(nodes[i][5])
				break

def init_filename(filename):
    shell("cat blank.mp3 > _" + filename + ".mp3", shell=True)
예제 #30
0
 def restart_tor(self, num=3):
     shell('service tor restart')
     sleep(1.5)
     self.update_ip(num)
예제 #31
0
	def lt_proc_txt(self, type, string):
		string = bytes(string, 'UTF-8')
		deformated = shell("apertium-destxt", input=string)
		piped = self.lt_proc(type, deformated)
		reformated = shell("apertium-retxt", input=piped)
		return str(reformated, 'UTF-8')
예제 #32
0
 def stop_tor():
     shell('service tor stop')
예제 #33
0
def run_cmd(cmd, multi=False):
    show_command(cmd, multi=multi)
    exit = shell(cmd, shell=True)
    return exit == 0
예제 #34
0
파일: setup.py 프로젝트: Pythonz/PIRB
#!/usr/bin/env python

from subprocess import Popen as shell

shell("python setup.py install", shell=True, cwd="deps/APScheduler").wait()