I want to be able to log in to my AWS postgres database from a remote machine. I am using the following Fabric script:
import sys
from fabric.api import env, run, abort
env.port = 123
env.use_ssh_config = True
def setuser(user):
"""Sets the ssh user for the fabric script"""
env.user = user
env.password = 'mypassword'
def setenv(server):
"""Sets the environment for the fabric script"""
env.hosts = ['staging']
def sync():
# log into AWS server
run("psql --host=staging.xxx.rds.amazonaws.com --username=x_user --port=5432 --password --dbname=x_database")
run("mypassword")
I run this Fabric script using the following command:
fab -f sync_staging.py sync --password=mypassword
This logs me into the remote machine, runs the line run("psql .... and then it prompts me for a password:
[stage] out: Password for user x_user:
Is there any way that I can supply the password (or respond to the prompt) such that it logs me in automatically?
There are 2 ways of solving this that I know of:
.pgpass password file in your home directory on remote host
PGPASSWORD env variable (set on remote host)
If you need to set an environment variable on remote host, use with shell_env(PGPASSWORD='mypassword'), Fabric docs here: fabric.context_managers.shell_env
Hope it solves your problem.
Related
I'm working with fabric3 (https://pypi.python.org/pypi/Fabric3) , a python 3 port of fabric.
I have the following function wchich I'm running locally in win7 using git-bash:
#roles('production')
def dir():
env.key_filename = '~/.ssh/deploy'
local("git push mysite master")
run('pwd')
run('ls')
code_dir = '/home/deploy/mysite'
with cd(code_dir):
run('pwd')
run('git reset --hard master')
run('ls -la')
output:
$ fab dir
[deploy#198.x.x.x] Executing task 'dir'
[localhost] local: git push mysite master
deploy#198.x.x.x's password:
When I run the function, I get asked for the password. It seems to be ignoring the key. How can I get the function to use the prescribed key?
I added git as a user to my .ssh/config file and it now appears to work.
Host deploy
HostName 198.x.x.x
User deploy
PreferredAuthentications publickey
IdentityFile ~/.ssh/deploy
IdentitiesOnly yes
Host 198.x.x.x
HostName 198.x.x.x
User git
IdentityFile ~/.ssh/deploy
When I use Fabric to connect to a host with the wrong SSH key, it prompts for a password instead of failing.
Here is the output from SSH:
$ ssh -i 'ssh_key_file' user#host
Permission denied (publickey,keyboard-interactive).
And here is what Fabric does with the following file:
# fabfile.py
from fabric.api import env, execute, run, task
env.hosts = ['host']
env.key_filename = 'ssh_key_file'
#task
def do_something():
run('echo hello')
execute(do_something)
Fabric's output:
$ python fabfile.py
[104.236.30.93] Executing task 'do_something'
[104.236.30.93] run: echo hello
[104.236.30.93] Login password for 'deploy':
How can I get Fabric to fail immediately with preferably a Permission denied (publickey,keyboard-interactive). error message, instead of prompting for a password?
It also affects other prompts (like the one for entering env.host_string) but you can do this with the env.abort_on_prompts = True (--abort_on_prompts).
When Fabric aborts on a prompt, it throws the built-in SystemExit exception that can be caught in case the programmer wants to select another SSH key or username to login with.
See the env documentation.
I have windows 7
I am trying:
env.hosts = ['xxx.xx.xx.xxx', 'xxx.xx.xx.xxx', 'xxx.xx.xx.xxx']
env.user = 'root'
env.key_filename = 'C:\Users\Doniyor\Desktop\ssh\secure-life\privkey.ppk'
def dm():
app_path = '/var/www/myproj/'
env_path = '/var/www/virtualenvs/myproj'
with cd(env_path):
run('. bin/activate')
with cd(app_path):
run('git pull origin master')
run('python manage.py collectstatic --settings=myproj.settings')
run('python manage.py migrate --settings=myproj.settings')
run('touch conf/uwsgi.ini')
But it keeps asking for root password:
what is missing here? I am fighting for almost 2 days now for it..
Add that private key as an SSH key for user root on all those servers with:
ssh-copy-id root#123.45.56.78
Make sure the SSH Agent is also running. SSH Agent is what uses your private key for authentication when you try to login to a remote server using SSH. Check Running SSH Agent when starting Git Bash on Windows
I'm writing a fab script to do a git pull on a remote server, but I get Permission denied (publickey,keyboard-interactive). when fabric runs the command.
If I ssh to the server and then do the pull, it works. (I've already setup the keys on the server, so it doesn't ask for passphrases, etc.)
Here's my fabric task:
import fabric.api as fab
def update():
'''
update workers code
'''
with fab.cd('~/myrepo'):
# pull changes
print colors.cyan('Pulling changes...')
fab.run('git pull origin master')
How do I get it to work with Fabric?
Edit: My server is a Google Compute instance, and it provides a gcutil tool to ssh to the instance. This is the command it runs to connect to the server:
ssh -o UserKnownHostsFile=/dev/null -o CheckHostIP=no -o StrictHostKeyChecking=no -i /Users/John/.ssh/google_compute_engine -A -p 22 John#123.456.789.101
The script is able to connect to the server AFAICT (it's able to run commands on the server like cd and supervisor and git status), it's just git pull that fails.
you need to edit fabfile like this in order to enable ssh agent fowarding option.
from fabric.api import *
env.hosts = ['123.456.789.101']
env.user = 'John'
env.key_filename = '/Users/John/.ssh/google_compute_engine'
env.forward_agent = True
def update():
'''
update workers code
'''
with cd('~/myrepo'):
# pull changes
print colors.cyan('Pulling changes...')
run('git pull origin master')
I'm trying to run netsh command on remote windows hosts (windows domain environment with admin rights). The following code works fine on local host but I would like to run it on remote hosts as well using python.
import subprocess
netshcmd=subprocess.Popen('netsh advfirewall show rule name=\”all\”', shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE )
output, errors = netshcmd.communicate()
The problem is that I'm no sure how/what method to use to initiate the connection to remote hosts and then run the subprocess commands. I cannot use ssh or pstools and would like try to implement it using existing pywin32 modules if possible.
I have used WMI module in a past which makes it very easy to query remote host but I couldn't find any way to query firewall policies over WMI and that's why using subprocess.
First you login the remote host machine using of pxssh modules Python: How can remote from my local pc to remoteA to remoteb to remote c using Paramiko
remote login of windows:
child = pexpect.spawn('ssh tiger#172.16.0.190 -p 8888')
child.logfile = open("/tmp/mylog", "w")
print child.before
child.expect('.*Are you sure you want to continue connecting (yes/no)?')
child.sendline("yes")
child.expect(".*assword:")
child.sendline("tiger\r")
child.expect('Press any key to continue...')
child.send('\r')
child.expect('C:\Users\.*>')
child.sendline('dir')
child.prompt('C:\Users\.*>')
Python - Pxssh - Getting an password refused error when trying to login to a remote server
and send your netsh command
I will recommend using Fabric, it's a powerful python tool with a suite of operations for executing local or remote shell commands, as well as auxiliary functionality such as prompting the running user for input, or aborting execution:
install fabric : pip install fabric
write the following script named remote_cmd.py:
"""
Usage:
python remote_cmd.py ip_address username password your_command
"""
from sys import argv
from fabric.api import run, env
def set_host_config(ip, user, password):
env.host_string = ip
env.user = user
env.password = password
def cmd(your_command):
"""
executes command remotely
"""
output = run(your_command)
return output
def main():
set_host_config(argv[1], argv[2], argv[3])
cmd(argv[4]))
if __name__ == '__main__':
main()
Usage:
python remote_cmd.py ip_address username password command