Netmiko ConnectHandler - for device with custom login prompt - netmiko

I have few Linux devices that is setup with customized login prompt which uses 5 parameters (username, password, Accountname, Userid, Userpassword)
As far i'm aware Netmiko ConnectHandler only has the option of Username and Password for the login/connect to a device. is there any other method that i can use in netmiko by which i can establish the ssh channel to this device?
$
$
$ssh -l support USLNXGWSVR
ACCOUNTNAME : tier1support
USERID : kevinstephan
PASSWORD: *********
Password: *********
[support#USLNXGWSVR~]$
[support#USLNXGWSVR~]$
[support#USLNXGWSVR~]$ uptime
00:19:44 up 117 days, 19:09, 1 user, load average: 0.00, 0.01, 0.05
[support#USLNXGWSVR~]$

Related

How to add environment variable value to YAML file?

I'm having .env file. which contains:
User_Name= username
Pass_Word= password
How to add the above variable values username and password only to the yaml.
I mentioned in this way:
Website:
USER:
Login: ${User_Name}
Pass: ${Pass_Word}
Expected Result while parsed in python file:
Login = username
Pass = password
But I'm getting strings like below while I actually need to get username and password:
Login = '${User_Name}'
Pass = '${Pass_Word}'
As I understand you need configuration like this:
username: "username"
password: "password"
website:
user:
login: ${username}
pass: ${password}

Email sending error in elastalert. SMTPSenderRefused: (530, '5.5.1 Authentication Required)

i got gmail authentication error. my config and error message as below
I already allowed less secure apps in gmail.
Config.yaml file email section as below
name: frequency_rule
type: frequency
index: security
num_events: 50
timeframe:
days: 1
filter:
- term:
host.keyword : "azure-2"
alert:
- email
email:
"to_address#gmail.com"
smtp_host: "smtp.gmail.com"
smtp_port: "465"
smtp_ssl: true
from_addr: "from_address#gmail.com"
user: "from_address#gmail.com"
password: "password"
Error message as below
PS C:\Users\smiforce-2ndPC\Downloads\Compressed\elastalert-master\elastalert-master> python -m elastalert.elastalert --verbose --config ./config.yaml --rule ./alert_rules/frequency4.yaml
INFO:elastalert:Starting up
INFO:elastalert:Queried rule frequency_rule4 from 2017-11-20 09:48 Central Standard Time to 2017-11-21 09:48 Central Standard Time: 24 / 24 hits
ERROR:root:Traceback (most recent call last):
File "C:\Users\smiforce-2ndPC\Downloads\Compressed\elastalert-master\elastalert-master\elastalert\elastalert.py", line 1246, in alert
return self.send_alert(matches, rule, alert_time=alert_time, retried=retried)
File "C:\Users\smiforce-2ndPC\Downloads\Compressed\elastalert-master\elastalert-master\elastalert\elastalert.py", line 1326, in send_alert
alert.alert(matches)
File "elastalert\alerts.py", line 451, in alert
self.smtp.sendmail(self.from_addr, to_addr, email_msg.as_string())
File "C:\Python27\lib\smtplib.py", line 737, in sendmail
raise SMTPSenderRefused(code, resp, from_addr)
SMTPSenderRefused: (530, '5.5.1 Authentication Required. Learn more at\n5.5.1 https://support.google.com/mail/?p=WantAuthError l4sm636961ioc.69 - gsmtp', 'from_address#gmail.com')
ERROR:root:Uncaught exception running rule frequency_rule4: (530, '5.5.1 Authentication Required. Learn more at\n5.5.1 https://support.google.com/mail/?p=WantAuthError l4sm636961ioc.69 - gsmt
The user and password fields should not be stored in the same config.yaml file but in another file which is referenced in config.yaml.
For instance, create another file named auth.yaml and add the user and password configuration into it:
user: "from_address#gmail.com"
password: "password"
Then in config.yaml you can reference that file using this setting:
smtp_auth_file: "/path/to/auth.yaml"

How to run ansible from linux to deploy on windows machines

Here is what I have after setting kerberos according to ansible:
http://docs.ansible.com/ansible/intro_windows.html
[libdefaults]
default_realm = MY.DOMAIN.COM
…
[realms]
MY.DOMAIN.COM = {
default_domain = my.domain.com
kdc = <domain-controller-server>.my.domain.com
kpasswd_server = <domain-controller-server>.my.domain.com
}
…
[domain_realm]
.my.domain.com = MY.DOMAIN.COM
…
I was able to create a kerberos ticket, here is my output:
root#alex-VirtualBox:/etc/ansible# klist
Ticket cache: FILE:/tmp/krb5cc_0
Default principal: <user_name>#MY.DOMAIN.COM
Valid starting Expires Service principal
04/07/2016 13:58:52 04/07/2016 23:58:52 krbtgt/MY.DOMAIN.COM#MY.DOMAIN.COM
renew until 04/08/2016 13:58:48
04/07/2016 14:02:20 04/07/2016 23:58:52 HTTP/<windows-target-server>.my.domain.com#MY.DOMAIN.COM
renew until 04/08/2016 13:58:48
So what I am trying to do is run ansible playbook or even a simple command on . But I am getting this error which I am pretty sure have nothing to do with ansible:
root#alex-VirtualBox:/etc/ansible# ansible windows -m win_ping --ask-vault-pass
Vault password:
<windows-target-server>.my.domain.com | FAILED! => {
"failed": true,
"msg": "kerberos: (('Unspecified GSS failure. Minor code may provide more information', 851968), ('Server not found in Kerberos database', -1765328377)), plaintext: 401 Unauthorized."
}
I even went ahead and created the keytab file:
> ktutil
ktutil: addent -password -p <user_name>#MY.DOMAIN.COM -k 1 -e rc4-hmac
provide password
ktutil: wkt <user_name>.keytab
ktutil: quit
But then I get different error:
root#alex-VirtualBox:/etc/ansible# ansible windows -m win_ping --ask-vault-pass
n2-2wbp-wbsvr01.na.msds.rhi.com | FAILED! => {
"failed": true,
"msg": "kerberos: (('An invalid name was supplied', 131072), ('Success', 100001)), plaintext: 401 Unauthorized."
}
Try to put the IP and Hostname of your Windows Host entry in /etc/hosts file and then try: https://github.com/diyan/pywinrm/issues/21#issuecomment-58958732 , https://github.com/diyan/pywinrm/issues/21#issuecomment-59084178
PS:
'Server not found in Kerberos database' - That usually means that the Linux host where you're running kinit is not joined to the domain (ie, it doesn't have a properly configured computer account in the domain). The existing docs unhelpfully omit that requirement...

Changing an AIX password via script?

I am trying to change a password of a user via script. I cannot use sudo as there is a feature that requires the user to change the password again if another user changes their password.
AIX is running on the system.
unfortunately, chpasswd is unavailable.
I have expected installed, but I am having trouble with that also.
here is what I thought would work
echo "oldpassword\nnewpasswd123\nnewpasswd123" | passwd user
However once run the script I am prompted with please enter user's old password
shouldn't they all be echoed in?
I am a beginner with shell scripting and this has been baffled.
You can try:
echo "USERNAME:NEWPASSWORD" | chpasswd
Use GNU passwd stdin flag.
From the man page:
--stdin
This option is used to indicate that passwd should read the new password from standard input, which can be a pipe.
NOTE: Only for root user.
Example
$ adduser foo
$ echo "NewPass" |passwd foo --stdin
Changing password for user foo.
passwd: all authentication tokens updated successfully.
Alternatively you can use expect, this simple code will do the trick:
#!/usr/bin/expect
spawn passwd foo
expect "password:"
send "Xcv15kl\r"
expect "Retype new password:"
send "Xcv15kl\r"
interact
Results
$ ./passwd.xp
spawn passwd foo
Changing password for user foo.
New password:
Retype new password:
passwd: all authentication tokens updated successfully.
In addition to the other suggestions, you can also achieve this using a HEREDOC.
In your immediate case, this might look like:
$ /usr/bin/passwd root <<EOF
test
test
EOF
You need echo -e for the newline characters to take affect
you wrote
echo "oldpassword\nnewpasswd123\nnewpasswd123" | passwd user
you should try
echo -e "oldpassword\nnewpasswd123\nnewpasswd123" | passwd user
more than likely, you will not need the oldpassword\n portion of that command, you should just need the two new passwords. Don't forget to use single quotes around exclamation points!
echo -e "new"'!'"passwd123\nnew"'!'"passwd123" | passwd user
You can try :
echo -e "newpasswd123\nnnewpasswd123" | passwd user
Just this
passwd <<EOF
oldpassword
newpassword
newpassword
EOF
Actual output from ubuntu machine (sorry no AIX available to me):
user#host:~$ passwd <<EOF
oldpassword
newpassword
newpassword
EOF
Changing password for user.
(current) UNIX password: Enter new UNIX password: Retype new UNIX password:
passwd: password updated successfully
user#host:~$
This is from : Script to change password on linux servers over ssh
The script below will need to be saved as a file (eg ./passwdWrapper) and made executable (chmod u+x ./passwdWrapper)
#!/usr/bin/expect -f
#wrapper to make passwd(1) be non-interactive
#username is passed as 1st arg, passwd as 2nd
set username [lindex $argv 0]
set password [lindex $argv 1]
set serverid [lindex $argv 2]
set newpassword [lindex $argv 3]
spawn ssh $serverid passwd
expect "assword:"
send "$password\r"
expect "UNIX password:"
send "$password\r"
expect "password:"
send "$newpassword\r"
expect "password:"
send "$newpassword\r"
expect eof
Then you can run ./passwdWrapper $user $password $server $newpassword which will actually change the password.
Note: This requires that you install expect on the machine from which you will be running the command. (sudo apt-get install expect) The script works on CentOS 5/6 and Ubuntu 14.04, but if the prompts in passwd change, you may have to tweak the expect lines.
Here is the script...
#!/bin/bash
echo "Please enter username:"
read username
echo "Please enter the new password:"
read -s password1
echo "Please repeat the new password:"
read -s password2
# Check both passwords match
if [ $password1 != $password2 ]; then
echo "Passwords do not match"
exit
fi
# Does User exist?
id $username &> /dev/null
if [ $? -eq 0 ]; then
echo "$username exists... changing password."
else
echo "$username does not exist - Password could not be updated for $username"; exit
fi
# Change password
echo -e "$password1\n$password1" | passwd $username
Refer the link below as well...
http://www.putorius.net/2013/04/bash-script-to-change-users-password.html
You can try
LINUX
echo password | passwd username --stdin
UNIX
echo username:password | chpasswd -c
If you dont use "-c" argument, you need to change password next time.
If you can use ansible, and set the sudo rights in it, then you can easily use this script. If you're wanting to script something like this, it means you need to do it on more than one system. Therefore, you should try to automate that as well.
For me this worked in a vagrant VM:
sudo /usr/bin/passwd root <<EOF
12345678
12345678
EOF
printf "oldpassword/nnewpassword/nnewpassword" | passwd user
#!/usr/bin/python
import random
import string
import smtplib
import sys
import os
from subprocess import call
import socket
user = sys.argv[1]
receivers = ["%s#domain.com" %user]
'''This will generate a 30 character random password'''
def genrandpwd():
return ''.join(random.SystemRandom().choice(string.ascii_lowercase + string.digits + string.ascii_uppercase + string.punctuation) for _ in range(30))
def change_passwd(user, password):
p = os.popen("/usr/bin/passwd %s" %user, "w")
p.write(password)
p.write("\n")
p.write(password)
p.close()
def chage(user):
agepasswd = call(["/usr/bin/chage", "-d", "0", "%s" %user])
def mailpwd(user, password):
sender = "admin#%s" %socket.gethostname()
subj = "!!!IMPORTANT!!!, Unix password changed for user %s" %user
text = "The password for the %s user has changed, the new password is:\n\n %s \n\n Note: The system will force to change the password upon initial login. Please use the password provided in the mail as your current password and type the password of your choice as the New password" %(user, password)
message = message = 'Subject: %s\n\n%s' % (subj, text)
smtpObj = smtplib.SMTP('mailrelay-server.domain.com')
smtpObj.sendmail(sender, receivers, message)
smtpObj.quit()
def main():
newpwd = genrandpwd()
change_passwd(user, newpwd)
chage(user)
mailpwd(user, newpwd)
if __name__ == "__main__":
main()

pexpect - run script.sh over ssh

I'm having trouble programmatically running a local script over ssh.
I'm unsure if this is a problem with the shell variable substitution on the local host.
When manually running,
ssh monit#server1 'bash -s' < /u02/splunk/splunk/etc/apps/Splunk_TA_nix/bin/cpu.sh
I get the expected output,
CPU pctUser pctNice pctSystem pctIowait pctIdle
all 11.21 0.00 1.50 0.31 86.98
0 0.00 0.00 0.00 0.00 100.00
1 3.00 0.00 1.00 0.00 96.00
....
but I get
bash: /u02/splunk/splunk/etc/apps/Splunk_TA_nix/bin/cpu.sh: No such file or directory
when running the following code,
splunk_bin_dir = '/u02/splunk/splunk/etc/apps/Splunk_TA_nix/bin'
hostname = 'server1'
username = 'monit'
password = 'monit#_'
command = "/usr/bin/ssh %(username)s#%(hostname)s 'bash -s' < %(splunk_bin_dir)s/cpu.sh" % locals()
print command
ssh_new_conn = 'Are you sure you want to continue connecting'
p = pexpect.spawn(command, timeout=360)
# Handles the 3 possible connection outcomes:
# a) Ssh to the remote host for the first time, triggering 'Are you sure you want to continue connecting'
# b) ask you for password
# c) No password is needed at all, because you already have the key.
i = p.expect([ssh_new_conn,'[pP]assword:',pexpect.EOF])
print ' Initial pexpect command output: ', i
if i == 0:
# send 'yes'
p.sendline('yes')
i = p.expect(['[pP]assword:',pexpect.EOF])
print 'sent yes. pexpect command output', i
if i == 0:
# send the password
p.sendline(password)
p.expect(pexpect.EOF)
elif i == 1:
# send the password
p.sendline(password)
p.expect(pexpect.EOF)
elif i == 2:
print "pexpect faced key or connection timeout"
pass
print p.before
These are the printed outputs,
/usr/bin/ssh monit#server1 'bash -s' < /u02/splunk/splunk/etc/apps/Splunk_TA_nix/bin/cpu.sh
Initial pexpect command output: 1
bash: /u02/splunk/splunk/etc/apps/Splunk_TA_nix/bin/cpu.sh: No such file or directory
pexpect is bumping into the [pP]assword line so I guess the password is being correctly passed,
Here the note from pexpect manual:
Remember that Pexpect does NOT interpret shell meta characters such as
redirect, pipe, or wild cards (>, |, or *). This is a common mistake.
If you want to run a command and pipe it through another command then
you must also start a shell.
This is the working line
command = """/bin/bash -c "/usr/bin/ssh %(username)s#%(hostname)s 'bash -s' < %(splunk_bin_dir)s/cpu.sh" """ % locals()

Resources