I need to connect to a remote server using a (non-python) script from terminal.
$./myscript <parameters>
Normally, I would need to enter the password. I have the following question, assuming a python script will run myscript:
How do I get the password from the user
How do I feed it into myscript?
If I understand the question correctly you would probably use the getpass function.
import getpass
password = getpass.getpass()
print 'You entered:', password
The major advantage is that the password will not be visible on the screen as the user enters it.
If you simply want to pass in arguments to your application you can use sys.argv.
import sys
if len(sys.argv) > 1:
print "First argument:", sys.argv[1]
If you need to pass on a password to a script executed by Python you can use subprocess call.
import getpass
import subprocess
password = getpass.getpass()
subprocess.call(["myscript", password ])
Related
I have created GuI in Visual Studio 2019.
There user will enter username and password and that i have to pass to python script. That when user will click on login button, python script will be triggered and output will be displayed.
My Tried python code is:
import paramiko
import time
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
hostname = input("Enter host IP address: ")
username = input("Enter SSH Username: ")
password = input("Enter SSH Password: ")
port = 22
ssh.connect(hostname, port, username, password, look_for_keys=False)
print("ssh login successfully")
#stdin,stdout,stderr = ssh.exec_command('show version')
#output = stdout.readlines()
#print(output)
Device_access = ssh.invoke_shell()
Device_access.send(b'environment no more \n')
Device_access.send(b'show version\n')
time.sleep(2)
output = Device_access.recv(65000)
print (output.decode('ascii'))
except:
print("error in connection due to wrong input entered")
But in this i am not getting how to link with input enter to Gui c# with python script. Please let me know how i can do.
Thanks in advance!
You could use arguments to call your Python Script.
Change the python script:
import paramiko
import time
import sys # Used to get arguments
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
hostname = sys.argv[1] # Skip 0th arg, since it is just the filename
username = sys.argv[2]
password = sys.argv[3]
port = 22
ssh.connect(hostname, port, username, password, look_for_keys=False)
print("ssh login successfully")
#stdin,stdout,stderr = ssh.exec_command('show version')
#output = stdout.readlines()
#print(output)
Device_access = ssh.invoke_shell()
Device_access.send(b'environment no more \n')
Device_access.send(b'show version\n')
time.sleep(2)
output = Device_access.recv(65000)
print (output.decode('ascii'))
except:
print("error in connection due to wrong input entered")
And change your C# code which calls the Script to something like this:
Process pythonScript = new Process();
pythonScript.StartInfo.FileName = "Your python script";
pythonScript.StartInfo.Arguments = $"{YouHostnameVar} {YouUsernameVar} {YourPasswordVar}"; // Start the script with the credentials as arguments
pythonScript.Start();
There are multiple approaches to incorporating a Python script with .NET C# code
I will try and give a basic overview, along with my suggestion, but ultimately, it will be up to you to figure out what works best.
IronPython
IronPython is an actual separate interpreter to translate Python code into the .NET Common Language Runtime (CLR). It works well for simple Python2 scripts that are not reliant on certain libraries.
Python.NET
Python.NET uses the normal Python interpreter. It simply provides a way to interface between Python scripts and .NET code.
System Diagnostics (My Suggestion)
The System Diagnostics C# tool allows you to run Python scripts as a system process. Not that this only runs the Python script. In order to transfer information between the Python script and the C# code, you will need some kind of shared file. I recommend setting up a folder where you save information used by both the C# and Python programs.
For a simple implementation of System Diagnostics, along with notes on the particular way System Diagnostics is being called, check out this: https://www.dotnetlovers.com/article/216/executing-python-script-from-c-sharp
EDIT Based on Paul Sütterlin Answer
As opposed to using a file to share information, Paul correctly points out that you can pass information as arguments. He also points out the simple process tool in C#, which is easier to set up than System Diagnostics. I recommend you read the article I linked to see which solution best suits you. System diagnostics gives you more options, but they do have to be configured.
I am trying to write a python script which uses scp to log into a HPC cluster (where I have an account) and transfer files from the cluster to my local system. I am able to os.system() to type the scp command. But, after that, I am a bit confused about what I must do when I am asked for the password (assume my password is password). I have tried os.system('password') and print 'password', but they don't work.
This is the python script that I have written:
import os
import sys
password = 'password'
clusterpath = 'myname#cluster.hpc1.cs.univ.edu:/Projects/re* '
localpath = 'Projects/.'
os.system('scp ' + clusterpath + localpath)
When I execute this script, I am asked for the password of my cluster. How can I enter the password of the cluster account through this python script?
How to Skip the login password prompt if not entered or password is wrong..
I have Below python fabric code.. which works fine but stucks with wrong passwords..
import sys
from fabric.api import *
env.skip_bad_hosts=True
env.command_timeout=60
env.user = 'test'
env.shell = "/bin/sh -c"
env.warn_only = True
env.password = 'mypass'
def read_hosts():
env.hosts = [line.strip() for line in sys.stdin.readlines()]
def cyberark():
with settings(warn_only=True):
output=sudo("/monitor.sh",shell=False)
When i run it, it stands there only until i break it manually...
[pc-karn] Executing task 'cyberark'
[pc-karn] sudo: /monitor.sh
[pc-karn] Login password for 'test':
Is there anyway to set the env where if the password given wrong with 2 consecutive sequence and it will go to the next host in line.
You can use this parameters -
with settings(abort_on_prompts=True):
This parameter terminate the program when prompt the user for input. You can read about it here.
I don't know if this solve your problem, as far as i know Fabric what you are looking for is not possible, but at least you know your program always terminate, and can fix the passwords issue.
When I want to dodge a password prompt but continue my script on fail, I use abort_on_prompts=True and catch the SystemExit exception that is raised by abort_on_prompt.
try :
with settings(abort_on_prompts=True):
output=sudo("/monitor.sh",shell=False)
except SystemExit as se :
print "What I want to do when it fails"
I am writing a simple python script to test connectivity to multiple linux hosts running centos on them. For this I am thinking of using pexpect module and ssh . pexpect will send the password stored in a variable when prompted for. The problem is that how to check if the password was accepted successfully or not. Is there a way to do so. The code is given below. Please add you expert comments.
This example has code written to ssh to localhost only.So a for loop is not yet included.
import pexpect
from getpass import getpass
import sys
# Defining Global Variables
log_file = '/tmp/AccessValidation'
# Getting password from user and storing in a variable
passs = getpass("Please enter your password: ")
# Connect to server using ssh connection and run a command to verify access.
child = pexpect.spawn("ssh -q -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no 127.0.0.1 'uptime'")
child.expect('Password:')
child.sendline(passs)
One of the things you could do is to have an expect for the command prompt. So if your prompt is: someuser#host$ you could do child.expect(".*\$").
Another thing you could do is to have multiple expects and then check those against the ones you want. For example:
i = child.expect([".*\$", "Password Incorrect"])
if i != 0:
print "Incorrect credentials"
else:
print "Command executed correctly"
You can view some examples within Pexpect's readthedocs page. Pexpect also has the pxssh class that is specialized to handle ssh connections and may be of some use also. I personally haven't used it but the syntax seems the same, just with more options relating to ssh.
Thanks Cory Shay for helping me figure out the correct way to solve my problem . Below is the code I have written and this works.
import pexpect
from getpass import getpass
import sys
# Defining Global Variables
log_file = '/tmp/AccessValidation'
# Getting password from user and storing in a variable
passs = getpass("Please enter your password: ")
# Connect to server using ssh connection and run a command to verify access.
child = pexpect.spawn("ssh -q -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no 127.0.0.1 'hostname' ")
child.expect('Password:')
child.sendline(passs)
result = child.expect(['Password:', pexpect.EOF])
if result == 0:
print "Access Denied"
elif result == 1:
print "Access Granted"
I am new to python and have run in to a problem with the following.
This is a code snippet from the Splunk api, thats used to connect to a splunk server then print the installed apps.
import splunklib.client as client
HOST = "server.splunk"
PORT = 8089
USERNAME = "UserABC"
PASSWORD = "Passw000rd"
# Create a Service instance and log in
service = client.connect(
host=HOST,
port=PORT,
username=USERNAME,
password=PASSWORD)
# Print installed apps to the console to verify login
for app in service.apps:
print app.name
I've tried it on my system in cmd and it works fine. However I intend to use this function in a Robot Framework test so the function needs to be defined in order to have a keyword I can use. I'm guessing something like the following:
import splunklib.client as client
def setServer(HOST, PORT, USERNAME, PASSWORD):
HOST = "server.splunk"
PORT = 8089
USERNAME = "UserABC"
PASSWORD = "Passw000rd"
service = client.connect(host=HOST,port=PORT,username=USERNAME,password=PASSWORD)
for app in service.apps:
print app.name
print ("\n")
My problem is when I run this nothing is printed to CMD at all. Any ideas
Thanks
A print in Python library is not displayed on the console of Robot Framework, that is the expected behaviour. If you want to check that the piece of code was run and the print was done, check the log.html produced by Robot. It should contain your print. Then if you really want to display something on Robot Console, then you have to use Log To Console keyword from your Robot Test. But as your print is in the python lib, you will have to import BuiltIn lib within your Python code. With all that, you should be fine.