I have a python script that does a zipping of a few files. For zipping the files with a password I use os.system() function and pass my zipping command ie. zip -j -re <file_path> <to_path>. This command asks for a password on the terminal which I have to put manually on the terminal like this.
Enter password:
Verify password:
I want to hardcode my password and pass it when the terminal asks for a password.
I tried to send the passwords using os.system(password) twice thinking that it will take it but it did not work.
cmd = "zip -j -re {} {}".format(DUMPSPATH,TEMPPATH)
passwrd = 'hello123'
os.system(cmd)
os.system(passwrd)
os.system(passwrd)
How do I send arguments using python to fill passwords automatically?
When you call os.system(), you are sending a command to your shell to run. So calling os.system(passwrd) is sending your password as a standalone command to be run by the shell, which is not what you want here.
The zip program features a -P password argument that allows you to specify the password to encrypt zip files when you initially run the command without having to manually input it for batch jobs. So essentially your code should be changed to something like this:
passwrd = 'hello123'
cmd = "zip -j -re -P {} {} {}".format(passwrd, DUMPSPATH,TEMPPATH)
os.system(cmd)
Another side note, it's recommended to use the subprocess module instead of resorting to os.system, so take a look at subprocess.Popen if you get a chance.
It's nice computer_geek has found the correct command line argument (I can't see it listed over here, but it works), but I absolutely HAVE to post my ludicrous solution (for posterity). NOTE - requires xdotool installed on your system.
import subprocess
DUMPSPATH = ""
TEMPPATH = ""
pwd = "lala"
zipper = subprocess.Popen(['zip','-j','-re',DUMPSPATH,TEMPPATH])
subprocess.run(['xdotool','type',pwd])
subprocess.run(['xdotool','key', 'Return'])
subprocess.run(['xdotool','type',pwd])
subprocess.run(['xdotool','key', 'Return'])
zipper.wait()
Related
I need to run an executable file that works only with command prompt multiple times.It is used to retrieve data Information based on the Details of the framenumbers and it ranges only between 0 to any postive value. And I have this framenumber data in a Excel file and i want it to loop through the range of framenumber. This is the part of command --start {framenumber1} --end {framenumber2} where it should be changed for each execution. i also Need admin rights to run this executable.
Is there any possible way of automating this workflow in python for using the command prompt multiple times with slightly different Input? Any Suggestion would be very helpful
Found the solution of using os.system() invoking to solve it. Here is the gist of code of how to Access the command prompt using python with admin Rights.
def is_admin():
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except:
return False
if is_admin():
df=pd.read_excel(r'D:\final_xxxx.xlsx',sep=',')
for i,x in zip(df['framenumber'],df['C']):
os.chdir(os.path.dirname(os.path.abspath(r'C:\Users\xxxx\Desktop\xxxxxxx\xxxv1.02\xxx\xxx.exe')))
if i==i:
k=math.trunc(i)
j=k
#executable operation running in python for command prompt till the loop ends
os.system(r'xxxx.exe --file "D:\xxxx\2020-07-27_xxxxx.xxxx" --output "D:\xxxx" --start {} --end {}'.format(j,j))
ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, " ".join(sys.argv), None, 1)
I'm trying to write a script to log in to 1 of 30+ accounts on a single ftp site which I use for work.
The behavior that I'd like to see:
$ ftp ftp.someplace.com
connected blah blah
220 blah blah ready...
Name (something): username
Password: <enter password>
couple lines saying successful login
ftp> <manually enter commands such as ls, cd, get, put, etc>
I've tried this in Python with ftplib using FTP.connect()/.login(), but nothing that I found in the ftplib relinquishes control and makes the ftp session interactive.
My next step was to try curl:
curl ftp://user:password#ftp.someplace.com
This executes and exits with return code 0.
Lastly, I tried ftp from the CLI in a method I would call it from a script:
ftp ftp.someplace.com <<END_SCRIPT
> quote USER username
> quote PASS password
> END_SCRIPT
This executes and exits with return code 0.
Is there a way to write a script to do this? I'd prefer this in python, but I'm okay with making a bash subprocess call. At this point I'm looking at some complex .netrc entry but I feel like I'm going down a rabbit hole.
Thanks for your help!
**************EDITED AFTER ANSWERED WITH PYTHON IMPLEMENTATION****************
The following 2 lines in python work:
process = subprocess.Popen("lftp -e ls -u {0},{1} ftp.someplace.com".format(username,password), shell=True)
output, error = process.communicate()
Would installing lftp be feasible? It has a flag, -e, that may suit your needs:
-e cmd execute the command just after selecting the server
After it executes the command it stays interactive. You could use the following approach where you have one file per account that has the following pattern (name this one, say, user1.lftp:
open ftp://user1:password#ftp.someplace.com
And when you want to connect as user1:
lftp -e 'source user1.lftp'
This will drop you to a prompt from which you can execute ftp commands. You could make it more convenient by defining function like the following in your .bashrc:
lftp-open() {
lftp -e "source $1.lftp"
}
And then it would be as simple as:
$ lftp-open user1
Obviously the downside of this, or probably of any approach to automating ftp login, is the requirement to store your password in plaintext, so you'd want to ensure that you have the proper read permissions set on the *.lftp files.
I am using Python 2.7.5, since this version is installed on the machine which I want to run script.
I have created a simple GUI in Tkinter, with button and text input.
Now in one input I provide the ip, or hostname of server, in next step I read the value of input fields and send it to linux bash terminal, and here I have a problem.
Reading the value from input field(works good)
nazwa_ip = self.Input_IP_hostname.get("1.0", 'end-1c')
and next:
os.system('gnome-terminal --window-with-profile=MY_PROFILE -e "ssh -t user_name#nazwa_ip"')
and here is the problem, because it wont change "nazwa_ip" to the read value. That comand send to terminal:
ssh -t user_name#nazwa_ip
but i want to send:
ssh -t user_name#ip_adres_from_input_field
Can somebody help me to resolve the issue?
according to the Python docs, it is recommended that os.system be replaced with the subprocess module .
status = os.system("mycmd" + " myarg")
# becomes
status = subprocess.call("mycmd" + " myarg", shell=True)
String formatting will work here:
os.system('gnome-terminal --window-with-profile=MY_PROFILE -e "ssh -t user_name#%s"' % nazwa_ip)
Using the subprocess method might be better to do this.
import subprocess
nazwa_ip = self.Input_IP_hostname.get("1.0", 'end-1c')
ssh_param = "ssh -t user_name#{}".format(nazwa_ip)
subprocess.call(['gnome-terminal', '--window-with-profile=MY_PROFILE', '-e', ssh_param])
Whilst running a subprocess is easy, starting one in a graphical terminal that behaves exactly like one the user launched is a little tricker. You could use my program interminal (link), which basically does what Stephen Rauch's answer does with gnome-terminal, but via a shell so that user environment variables and aliases etc are all available, which could be useful on the offchance that they affect how ssh runs.
You would use it from Python like this:
import subprocess
subprocess.Popen(['interminal', 'ssh', '-t', 'username#{}'.format(ip_address)])
I am looking for a way to execute multiple commands in the same shell instance using a separate function for each, something that I can define when the shell process opens/closes and can pass commands to.
so far all the answers I have found have only been in a single function
ie:
#!/usr/bin/env python
from subprocess import check_call
check_call(r"""set -e
ls -l
<some command> # This will change the present working directory
launchMyApp""", shell=True)
I need the same effect but with each command in a different function like
shell.open()
shell.exec("dir")
shell.exec("cd C:/Users/" + User + "/Desktop)
shell.close()
if you are wondering whyyy it has to be separate the command to run is coming from user input. yes I realize that is a security risk, but security isn't a problem in this case, as its purely an educational venture and not going to be used for anything
you could use subprocess.check_call(cmds_str, shell=True) in conjunction with multiple commands in the same line: How to run two commands in one line in Windows CMD?
You could build each command individually and add them to a list, and then use ' & '.join(cmd_list) to get cmds_str.
I don't use Windows but it works on Linux.
You can try pexpect with cmd.exe
import pexpect
child = pexpect.spawn("cmd.exe")
child.expect_exact("> ")
#print(child.before.decode('utf-8'))
print(child.before)
child.sendline("dir")
child.expect_exact("> ")
print(child.before)
child.sendline("cd C:/Users/" + User + "/Desktop")
child.expect_exact("> ")
print(child.before)
It runs cmd.exe, sends command in child.sendline() and looks for prompt child.expect_exact("> ") to get all text generated by command child.before.
I have created a fabfile with multiple hosts.
I am automating my experiment. When i run the command "sudo adduser --ingroup hadoop hduser" it will ask for the following.
New unix password
confirm Password.
Full Name
Room,Ph,etc
is this information Correct? Y/N
I would like to pass all this information as part of script without prompting user. How can i do this ?
Thanks
Navaz
Why didn't you just use pipes?
For example, for an automated auto accept, just use yes, that just outputs a neverending stream of y.
yes | rm *.txt
in your case:
local('echo 'your_super_password\n' | sudo adduser --ingroup hadoop hduser')
Another option is to use fexpect, an extension of fabric that enables you to respond to prompts:
from ilogue.fexpect import expect, expecting, run
prompts = []
prompts += expect('What is your full name?','John Doe')
prompts += expect('is this information Correct? Y/N','Y')
with expecting(prompts):
sudo('adduser --ingroup hadoop hduser')