How to pass arguments to linux command prompt using python script - python

Demo.py
import os
f = os.popen('passwd')
output:
Enter Existing Password: (This one i want program to enter )
I am running this python program which prompts me to Enter existing password. But i want to send that existing password through the program.
is there any way i could pass that value to command prompt via program.

We can achieve this by using python's expect module. I have written the sample code:
#!/usr/bin/python
import pexpect
import sys
child = pexpect.spawn('passwd')
child.logfile=sys.stdout
child.expect("UNIX password:")
child.sendline('guest')
child.expect('Enter new UNIX password:')
child.sendline('guest')
child.expect('Retype new UNIX password:')
child.sendline('guest')
You can also check more details of expect module at http://www.pythonforbeginners.com/systems-programming/how-to-use-the-pexpect-module-in-python

Related

How can i pass a input variable to subprocess.popen

import subprocess
import sys
password_d=raw_input("Input password")
prog = subprocess.Popen(['runas', '/user:KP\svc','cmd.exe'],universal_newlines=True,stdin=subprocess.PIPE,stdout=sys.stdout)
prog.stdin.write(password_d)
prog.communicate()[0]
This is my code. I am trying to login as another user through runas.exe and provide the password through already stored input object password_d which is taken from the user.
When i try to do this it says the password is incorrect. How can i achieve this in python and how can i print what is being fed as input. any leads would really be helpful.

How to use getpass() to hide a users password as it is entered [duplicate]

This question already has answers here:
"GetPassWarning: Can not control echo on the terminal" when running from IDLE
(4 answers)
Closed 5 years ago.
I am trying to make a small program which checks the strength of the user password. When the user is prompted to enter their password I want the input to show as asterisks or dots instead of the text input. Is there a way of hiding this input.
I have used getpass to try and hide the input without success.
from getpass import getpass
passwd = getpass('Please enter your password')
This gives me the following warning message:
Warning (from warnings module):
File "C:\Program Files (x86)\Python36-32\lib\getpass.py", line 100
return fallback_getpass(prompt, stream)
GetPassWarning: Can not control echo on the terminal.
Warning: Password input may be echoed.
Please enter your password: this_is_my_password
The password is entered on the line but instead of coming up with astrisks it comes up with the original characters.
As the program will check the strength of the password I need to have something that does not save the password as the asterisks but as its original characters.
As well as this is there any way of incorporating a way of showing the user password if they perform an action. I was considering using a button but that is an area in Python I am not confident with so could I program in another way with a specific key.
Sudo code for project.
userPass = hidden(input("Please enter your password "))
if showPassword selected:
show the password
else:
move on with the rest of the program
The warning basically means you are running your program in an environment where Python cannot use the regular interactive IOCTL calls to implement the asterisks-only functionality. Running a program from inside your IDE basically causes the IDE to run the program in a pseudo-terminal. Try running it on the command line instead.
The getpass module contains a getpass function that works just like input(), except that it turns the terminal echo off.
The result is the password entered, which you can use to determine its strength or print as needed, but while the user is entering their password, nothing is printed except the prompt.
>>> from getpass import getpass
>>> passwd = getpass('Please enter your password')
Please enter your password
>>> print passwd
This is my password

Trouble with masking password input in Python

I am using Python. I am making a script where the user has to enter the password in the terminal.
I have already found a solution on this website by using the getpass module.
new_password=getpass.getpass(prompt="Type new password: ")
The problem is I get a warning and the password input gets displayed as well.
Warning (from warnings module):
File "C:\Python34\lib\getpass.py", line 101
return fallback_getpass(prompt, stream)
GetPassWarning: Can not control echo on the terminal.
Warning: Password input may be echoed.
Use command prompt as admin to run this program.
Reason is because system environment where stdin, stdout and stderr are connected to /dev/tty, or another PTY-compliant device.
The IDLE REPL does not meet this requirement.
And change new_password=getpass.getpass(prompt="Type new password: ") to new_password=getpass.getpass("Type new password: ") if you are using Windows OS or new_password=getpass.getpass("Type new password: ", None) for Linux distributions.
This would help you for sure:
import getpass
pw = getpass.getpass("Enter Your Password Here: ")
if pw == "password":
print("You are Welcome...")
else:
print("Sorry! You're are not allowed.")
As per Python documentation:
getpass.getpass([prompt[, stream]])
Prompt the user for a password without echoing. The user is prompted using the string prompt, which defaults to 'Password: '. On Unix, the prompt is written to the file-like object stream. stream defaults to the controlling terminal (/dev/tty) or if that is unavailable to sys.stderr (this argument is ignored on Windows)
Changed in version 2.5: The stream parameter was added.
Note: If you call getpass from within IDLE, the input may be done in the terminal you launched IDLE from rather than the idle window itself.
Using a normal terminal with this code:
import getpass
new_password=getpass.getpass(prompt="Type new password: ")
print(new_password)
Will work alright, but if we try the same with IDLE we'll get the error you've exposed in your question.
Now, if we look at the docs here you'll see this is intended, it says:
Note If you call getpass from within IDLE, the input may be done in
the terminal you launched IDLE from rather than the idle window
itself.

Python - How to take input from command line and pipe it into socket.gethostbyaddr("")

I have been scouring the internet looking for the answer to this. Please not my python coding skills are not all that great. I am trying to create a command line script that will take the input from the command line like this:
$python GetHostID.py serverName.com
the last part is what I am wanting to pass on as a variable to socket.gethostbyaddr("") module. this is the code that I have so far. can someone help me figure out how to put that variable into the (" "). I think the "" is creating problems with using a simple variable name as it is trying to treat it as a string of text as appose to a variable name.
here is the code I have in my script:
#!/bin/python
#
import sys, os
import optparse
import socket
remoteServer = input("Enter a remote host to scan: ")
remoteServerIP = socket.gethostbyaddr(remoteServer)
socket.gethostbyaddr('remoteServer')[0]
os.getenv('remoteServer')
print (remoteServerIP)
any help would be welcome. I have been racking my brain over this...
thanks
The command line arguments are available as the list sys.argv, whose first element is the path to the program. There are a number of libraries you can use (argparse, optparse, etc.) to analyse the command line, but for your simple application you could do something like this:
import sys
import sys, os
import optparse
import socket
remoteServer = sys.argv[1]
remoteServerIP = socket.gethostbyaddr(remoteServer)
print (remoteServerIP)
Running this program with the command line
$ python GetHostID.py holdenweb.com
gives the output
('web105.webfaction.com', [], ['108.59.9.144'])
os.getenv('remoteserver') does not use the variable remoteserver as an argument. Instead it uses a string 'remoteserver'.
Also, are you trying to take input as a command line argument? Or are you trying to take it as user input? Your problem description and implementation differ here. The easiest way would be to run your script using
python GetHostID.py
and then in your code include
remoteServer = raw_input().strip().split()
to get the input you want for remoteserver.
you can use sys.argv
for
$python GetHostID.py serverName.com
sys.argv would be
['GetHostID.py', 'serverName.com']
but for being friendly to the user have a look at the argparse Tutorial
In Python 2, input reads text and evaluates it as a Python expression in the current context. This is almost never what you want; you want raw_input instead. However, in Python 3, input does what raw_input did in version 2, and raw_input is not available.
So, if you need your code to work in both Python 2 and 3, you should do something like this after your imports block:
# Apply Python 3 semantics to input() if running under v2.
try:
input = raw_input
def raw_input(*a, **k):
raise NameError('use input()')
except NameError:
pass
This has no effect in Python 3, but in v2 it replaces the stock input with raw_input, and raw_input with a function that always throws an exception (so you notice if you accidentally use raw_input).
If you find yourself needing to smooth over lots of differences between v2 and v3, the python-future library will probably make your life easier.

Python inside bash Input Error

I have inserted python code inside bash script like this:
#!/bin/bash
echo "You are in Bash"
python <<END
# -*- coding: utf-8 -*-
import os
import sys
import getpass
print "You are in python"
username=raw_input('Bitbucket Username : ')
END
echo "Python ended"
But the problem is I am not able to take input using raw_input or input when I insert python in bash. Python alone works fine. What is the problem here in my code?
Instead of a heredoc, just user the -c parameter to pass a command:
$ python -c "username = raw_input('Enter name: ')
print 'Hello', username
"
Enter name: Chris
Hello Chris
Once you say END, you are telling bash that your program is over. Bash gives your lines as input to Python. If you are in python, type each line that you wrote there, regardless of what prompt, and when you are done, signify EOF by Ctrl-D on linux, Ctrl-Z on windows. You will see that raw_input() will have a EOFError. That is what bash is doing. It gives Python each line, and then says "We're done. Send EOF". It pays no attention to what prompt is given. It doesn't know that you are asking for input. This is a useful feature, however, because if it didn't have that, there would be nothing telling Python to exit...ever. You would have to send KeyboardInterrupt to get that program to exit.

Categories

Resources