Solved

VBS script to use putty/plink to login to Unix - run command - retrieve answer into variable

Posted on 2014-09-11
18
7,119 Views
Last Modified: 2014-09-23
Greetings,

I need to create a VBS script do the following - all in the background and not verbos:

1. Call putty/plink and ssh to a Unix (or Linux) server with user ID and password.
2.  Run a specific command to find out if the system is primary or backup (for failover)
3. Feed the answer into a variable and then rename a file to something else if the variable equals one server or the other.

I am familiar enough with VB at this point to know what to do after I get the value in the variable but I have no idea how to log in to a Unix/Linux server via ssh from a windows system, run a unix command, get retrieve the command result and bring it back.

Any help would be great.  I am not opposed to using something other than VB - it's just that I'm more familiar with that than anything else.

Thanks!
0
Comment
Question by:yccdadmins
  • 10
  • 8
18 Comments
 
LVL 37

Assisted Solution

by:Gerwin Jansen
Gerwin Jansen earned 500 total points
ID: 40324231
What have you got already?

The part where you login to the Linux/Unix server is not that difficult, a basic (cmd) script looks like this:

@echo off
setlocal enableextensions
for /f "tokens=*" %%a in (
'c:\path_to\plink username@your_hostname -pw password command_to_run'
) do (
set myvar=%%a
)
echo %myvar%

Open in new window


The above will run command_to_run and set it's output in the myvar variable (and echo it).

Where do you want that file renamed? You could check the output of myvar and take some action then, maybe another ssh to rename that file?
0
 

Author Comment

by:yccdadmins
ID: 40324242
What you have shown me looks like exactly what I was missing.  Once I get the variable I can integrate it with my existing case statements that already edit shortcuts on a server based on AD group membership.  I'm going to try this tomorrow.

 Basically, all end users using an RDS server have the wrong link if we have a failover.  We've tried providing them with links to both systems but they always seemed to log in to the wrong server no matter what we do.  Next best thing is this - automate the process and update their link in the background.

Will let you know how it goes.
0
 

Author Comment

by:yccdadmins
ID: 40326327
Ok - tried it and got an error on line 3 - character 5.  Error was:

Error: Expected identifier
Code: 800A03F2

I'm looking up that code to see what I find.....
0
 

Author Comment

by:yccdadmins
ID: 40326336
Also - looking at plink to figure out how to force it to use ssh...
0
 

Author Comment

by:yccdadmins
ID: 40326485
Trying to easily decipher the instruction for Plink auto login is absolutely ridiculous.  Why to people assume you have hours to read through something, bouncing from one section to another.  I'm able to login via ssh using plink from command line but not able to decipher how to get it to work from a script...so far.
0
 
LVL 37

Expert Comment

by:Gerwin Jansen
ID: 40326495
plink is using ssh - you can verify by adding -P 22 (ssh port) like this:

'c:\path_to\plink username@your_hostname -pw password -P 22 command_to_run'

But about your error message: the script I've posted above is a cmd script (dos window), no vbs. Do you call other executables from vbs? To call plink from vbs you'd have to do a WshShell.Exec I believe.
0
 
LVL 37

Accepted Solution

by:
Gerwin Jansen earned 500 total points
ID: 40326517
Something like this:

Set shell = WScript.CreateObject("WScript.Shell")
pcmd = "c:\path_to\plink username@your_hostname -pw password command_to_run"
Set exec = shell.Exec(pcmd)
Set pout = exec.StdOut

While Not pout.AtEndOfStream
    pline = pout.ReadLine
    WScript.echo pline
Wend

Open in new window

0
 

Author Comment

by:yccdadmins
ID: 40326603
Using plink command line I was able to:

1. login to the Unix server - passing a username and password.
2. run the pwd command
3. write the results to an output file.

So far so good.  Now I just need to figure out how to:

1. get a script to ssh to the system but without exposing the password.
2. run the pwd command.
3. have the script put the results in a variable.

Closer at least.
0
 
LVL 37

Expert Comment

by:Gerwin Jansen
ID: 40327386
Without exposing the password: ssh keys can do that for you. You need help on that?

The output you want is in the pline variable above, that is what I verified working.
0
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 

Author Comment

by:yccdadmins
ID: 40328046
Yep - need help on that.  Basically, once I get the results from the command loaded into the variable I'm good from there.  I need help with everything leading up to it since I've never worked with putty/plink like this before.  I've gone through their docs but they bounce around too much.

Before I get into going without a password I wanted to get this working.  Line 2, character 4 seems to have generated and error:  "The system cannot find the file specified."

Something is off with the line "Set exec = shell.Exec(pcmd)" .  I'm running it from Windows 2008 server but that shouldn't have anything to do with it.

Investigating....
0
 
LVL 37

Expert Comment

by:Gerwin Jansen
ID: 40328291
Ssh keys sample will follow (mobile). That line 2 should contain the real path to your plink.exe - server 2008 is fine.
0
 
LVL 37

Assisted Solution

by:Gerwin Jansen
Gerwin Jansen earned 500 total points
ID: 40328837
How to setup ssh keys:  (on W2K8 machine)

- Generate a keypair using puttygen.exe - using the 'Generate' button, save the public and private key (keep them safe) in your <username>\.ssh folder
- Copy the public key text from the 'Key' window
- Logon to the Linux machine with the account you want to use, create a .ssh folder using:
   mkdir ~/.ssh
   chmod 600 ~/.ssh
- Create the autorized_keys file using:
   vi ~/.ssh/authorized_keys
- Paste the public key text into the autorized_keys file and save the file
   chmod 600 ~/.ssh/authorized_keys

Now you are prepared to connect using your public ssh key that is stored on the Linux server (target user's home folder).

Try the connection:

c:\path_to\plink.exe username@your_hostname -i c:\Users\<username>\.ssh\private_key_you_saved_before.ppk

When the connection works, you will have a prompt on the Linux host, exit that and change the command above:

pcmd = "c:\path_to\plink.exe username@your_hostname -i c:\Users\<username>\.ssh\private_key_you_saved_before.ppk command_to_run"
0
 

Author Comment

by:yccdadmins
ID: 40331506
Hello,

I had found the following link and used it to set up Putty for auto-login - worked perfectly and that hurdle is passed.

http://www.tonido.com/blog/index.php/2009/02/20/ssh-without-password-using-putty/#.VBtD4k10y9K

I'm testing the script portion now....
0
 

Author Comment

by:yccdadmins
ID: 40331514
The script ran perfectly!  No errors and the results from the command I ran popped right up.  So to confirm - pline is the variable that contains the results of what I run on the Unix side?
0
 
LVL 37

Expert Comment

by:Gerwin Jansen
ID: 40332031
Nice link about automating the login, I just wrote from the top of my head ;)

And yes, pline is the variable that will contain the output:

While Not pout.AtEndOfStream
   pline = pout.ReadLine
    WScript.echo pline
Wend

( so if you get more than one 'line' back from Unix, you get multiple popups ;) )
0
 

Author Comment

by:yccdadmins
ID: 40340216
This is great.  Below is my code to delete a link and then copy a new one based on the results.  I used basic commands like pwd for testing because the test account can't run the actual command at this time.  Everything works great except now I need to know how to make it run in the background with no user interaction like the popup....

On Error Resume Next

'-----------------------------------------------------
'Set variables for group determination etc.
'-----------------------------------------------------

Set WSHShell = CreateObject("Wscript.Shell")
Set WSHProcess = WSHShell.Environment("Process")
'Set objShell = CreateObject(wscript.shell)

Const DeleteReadOnly = TRUE

Set shell = WScript.CreateObject("WScript.Shell")

 	pcmd = "C:\Windows\System32\plink username@hostname -i C:\PuttyFiles\SSH-Keys\Tterm2PrivateKey.ppk pwd;exit"
 	Set exec = shell.Exec(pcmd)
	Set pout = exec.StdOut

 	While Not pout.AtEndOfStream
     		pline = pout.ReadLine
     		WScript.echo pline
 	Wend 

	Select Case pline

        Case "/home/username"


		Set objFSO = CreateObject("Scripting.FileSystemObject")
		set WshShell = WScript.CreateObject("WScript.Shell")
		tDesktopPath = WshShell.SpecialFolders("Desktop")
		objFSO.DeleteFile tDesktopPath & "\* Client.lnk"
		objFSO.CopyFile "C:\scripts\testshortcut\Prod1 Client.*", tDesktopPath, True 'OverwriteExisting

        Case "hostname"


		Set objFSO = CreateObject("Scripting.FileSystemObject")
		set WshShell = WScript.CreateObject("WScript.Shell")
		tDesktopPath = WshShell.SpecialFolders("Desktop")
		objFSO.DeleteFile DesktopPath & "\* Client.lnk"
		objFSO.CopyFile "C:\scripts\testshortcut\Prod1 Client.*", tDesktopPath, True 'OverwriteExisting

    End Select

Open in new window

0
 
LVL 37

Expert Comment

by:Gerwin Jansen
ID: 40340224
Remove the line:

WScript.echo pline
0
 

Author Comment

by:yccdadmins
ID: 40340355
Thanks - I had commented that out a bit ago and the only thing that pops up briefly now is the cmd screen but I put ";exit" after m command so it doesn't stay.

I had some errors in my case as far as deleting the exiting file but once I corrected that it works great.

Thanks for your assistance!
0

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

Well hello again!  Glad to see you've made it this far without giving up.  In this, the fourth installment of my popular series, I'm going to cover functions and subroutines, what they are, and why they are useful.  Just in case you stumbled onto th…
Deploying a Microsoft Access application in a Citrix environment is not difficult but takes a few steps. However, Citrix system people are often of little help, as they typically know next to nothing about Access. The script provided here will take …
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now