Welcome to the VanDyke Software Forums

Join the discussion today!


Go Back   VanDyke Software Forums > Scripting

Reply
 
Thread Tools Rate Thread Display Modes
  #1  
Old 03-25-2020, 04:22 PM
vikram1840 vikram1840 is offline
Registered User
 
Join Date: May 2019
Posts: 20
Connect Multiple Server Through same script

Hi Expert ,
I have to connect multiple SSH2 server comprising different host and credential,RUN some command and then connect SFTP to transefr files to local PC.

I want to perform access multiple host and SFTP with single python script only.

Presently I am able to do the same but for only one host at a time.
I had tried to call two different server but it runs for only one and not connecting other as showing one session already connected.

Please help.

Code:
# $language = "python"
# $interface = "1.0"

# Connect to an SSH server using the SSH2 protocol. Specify the
# username and password and hostname on the command line as well as
# some SSH2 protocol specific options.

def ENM(host,user_name,password):
    cmd = "/SSH2 /L " + user_name + " /PASSWORD " + password + " " + host
    crt.Session.Connect(cmd)
    crt.Screen.Synchronous = True
    row = crt.Screen.CurrentRow
    prompt = crt.Screen.Get(row, 0, row, crt.Screen.CurrentColumn - 5)
    prompt = prompt.strip()
    # crt.Dialog.MessageBox("not Connected and not send command")
    crt.Screen.WaitForString("]$")
    # crt.Dialog.MessageBox("Connected and now send command")
    crt.Screen.Send("cd EM_LTE\r")
    crt.Screen.WaitForString("]$")
    # crt.Dialog.MessageBox("one command send")
    crt.Screen.Send("./em.sh\r")
    crt.Screen.WaitForString("Enter Choice :")
    # crt.Dialog.MessageBox("Send ur choice")
    crt.Screen.Send("1\r")
    crt.Screen.WaitForString("]$")
    # crt.Dialog.MessageBox("Script run completed")
    sftp_transfer(user_name)


def sftp_transfer(user_name):
    # crt.Dialog.MessageBox("sftp comes")
    objSFTPTab = crt.GetScriptTab().ConnectSftp()
    objSFTPTab.Screen.Synchronous = False
    while True:
        strScreenText = objSFTPTab.Screen.Get2(
            1,
            1,
            crt.Screen.Rows,
            crt.Screen.Columns)
        if "sftp> " in strScreenText:
            break
        crt.Sleep(10)
    objSFTPTab.Screen.Synchronous = True
    objSFTPTab.Screen.Send("ls -l\r")
    strFileListing = objSFTPTab.Screen.ReadString("sftp> ")
    local_add= 'lcd C:\LTE'+ '\\' + user_name + "\r"
    objSFTPTab.Screen.Send(local_add)
    objSFTPTab.Screen.WaitForString("sftp> ")
    remote_add= "cd /home/shared/" + user_name + "/EM_LTE/Output/mobatch_RNC\r"
    objSFTPTab.Screen.Send(remote_add)
    objSFTPTab.Screen.WaitForString("sftp> ")
    objSFTPTab.Screen.Send("get all_ENM.txt\r")
    strResults = objSFTPTab.Screen.ReadString("sftp> ")
    if "100%" in strResults:
        vDataLines = strResults.split("\r\n")
        crt.Dialog.MessageBox("File transfer successful: \r\r" + vDataLines[-2])
    else:
        crt.Dialog.MessageBox("Failed to get file!\r\r" + strResults)

    # Close the SFTP tab once we're done
    objSFTPTab.Close


ENM(host1,user_name1,pswd1)
ENM(host2,user_name2,pswd2)

Last edited by vikram1840; 03-25-2020 at 04:24 PM.
Reply With Quote
  #2  
Old 03-25-2020, 05:29 PM
jdev's Avatar
jdev jdev is offline
VanDyke Technical Support
 
Join Date: Nov 2003
Location: Albuquerque, NM
Posts: 990
Quote:
Originally Posted by vikram1840 View Post
I want to perform access multiple host and SFTP with single python script only.

Presently I am able to do the same but for only one host at a time.
Sorry, the documentation for the Connect() method isn't quite as clear as it could be on how the Connect() method works.

If there is already a session connected in the script tab, the Connect() method will fail.

You will either need to call crt.Session.Disconnect() when you are finished calling your sftp_trasfer() routine, or you will need to use crt.Session.ConnectInTab() and work with the resulting tab object it returns.

--Jake
Attached Images
File Type: png Forum_14125_ConnectError.png (93.2 KB, 221 views)
__________________
Jake Devenport
VanDyke Software
Technical Support
YouTube Channel: https://www.youtube.com/vandykesoftware
Email: support@vandyke.com
Web: https://www.vandyke.com/support
Reply With Quote
  #3  
Old 03-26-2020, 05:12 AM
vikram1840 vikram1840 is offline
Registered User
 
Join Date: May 2019
Posts: 20
Connect Multiple Server Through same script

Hi Jake,

I have tried crt.Session.Disconnect() after sftp transfer get complete.
So it disconnect the current session and connect the new session but no any further command executing in that new session.
It just connect new session and then after it stops.
Could you please help.


Code:
def ENM(host,user_name,password):

    cmd = "/SSH2 /L " + user_name + " /PASSWORD " + password + " " + host
    crt.Session.Connect(cmd)
    crt.Screen.Synchronous = True
    row = crt.Screen.CurrentRow
    prompt = crt.Screen.Get(row, 0, row, crt.Screen.CurrentColumn - 5)
    prompt = prompt.strip()
    crt.Dialog.MessageBox("not Connected and not send command")
    crt.Screen.WaitForString("]$")
    crt.Dialog.MessageBox("Connected and now send command")
    crt.Screen.Send("cd EM_LTE\r")
    crt.Screen.WaitForString("]$")
    # crt.Dialog.MessageBox("one command send")
    #crt.Screen.Send("./em.sh\r")
    #crt.Screen.WaitForString("Enter Choice :")
    # crt.Dialog.MessageBox("Send ur choice")
    #crt.Screen.Send("1\r")
    #crt.Screen.WaitForString("]$")
    # crt.Dialog.MessageBox("Script run completed")
    sftp_transfer(user_name)





def sftp_transfer(user_name):
    # crt.Dialog.MessageBox("sftp comes")
    objSFTPTab = crt.GetScriptTab().ConnectSftp()
    objSFTPTab.Screen.Synchronous = False
    while True:
        strScreenText = objSFTPTab.Screen.Get2(
            1,
            1,
            crt.Screen.Rows,
            crt.Screen.Columns)
        if "sftp> " in strScreenText:
            break
        crt.Sleep(10)
    objSFTPTab.Screen.Synchronous = True
    objSFTPTab.Screen.Send("ls -l\r")
    strFileListing = objSFTPTab.Screen.ReadString("sftp> ")
    local_add= 'lcd C:\LTE'+ '\\' + user_name + "\r"
    objSFTPTab.Screen.Send(local_add)
    objSFTPTab.Screen.WaitForString("sftp> ")
    remote_add= "cd /home/shared/" + user_name + "/EM_LTE/Output/mobatch_RNC\r"
    objSFTPTab.Screen.Send(remote_add)
    objSFTPTab.Screen.WaitForString("sftp> ")
    objSFTPTab.Screen.Send("get all_ENM.txt\r")
    strResults = objSFTPTab.Screen.ReadString("sftp> ")
    if "100%" in strResults:
        vDataLines = strResults.split("\r\n")
        crt.Dialog.MessageBox("File transfer successful: \r\r" + vDataLines[-2])
    else:
        crt.Dialog.MessageBox("Failed to get file!\r\r" + strResults)

    # Close the SFTP tab once we're done
    objSFTPTab.Close
    crt.Session.Disconnect()

ENM(Host1,username1,paswd1)
ENM(host2,usernm2,pswd2)
Reply With Quote
  #4  
Old 03-26-2020, 11:46 AM
jdev's Avatar
jdev jdev is offline
VanDyke Technical Support
 
Join Date: Nov 2003
Location: Albuquerque, NM
Posts: 990
Quote:
Originally Posted by vikram1840 View Post
I have tried crt.Session.Disconnect() after sftp transfer get complete.
So it disconnect the current session and connect the new session but no any further command executing in that new session.
It just connect new session and then after it stops.
Could you please help.
Is the SFTP tab closing as you expect?

Your code uses objSFTPTab.Close which, while a valid python statement, won't likely do what you want... try actually calling the method as in: objSFTPTab.Close()

That's not necessarily the problem, though.

Can you post the text that is displayed in your terminal window when "it stops"?

Also, if you open the Script menu when "it stops", if the Cancel menu item is enabled, please click it, then...
What line in the script file does it say was being executed?

--Jake
__________________
Jake Devenport
VanDyke Software
Technical Support
YouTube Channel: https://www.youtube.com/vandykesoftware
Email: support@vandyke.com
Web: https://www.vandyke.com/support
Reply With Quote
  #5  
Old 03-26-2020, 12:20 PM
vikram1840 vikram1840 is offline
Registered User
 
Join Date: May 2019
Posts: 20
Connect Multiple Server Through same script

Hi,

I have tried with objSFTPTab.Close() and it worked but one issue I am facing is before closing the SFTP session it ask from user whether he wants to close the SFTP session or not.

As I have to automate the stuff so I want to avoid the manual intervention to close the SFTP session pop up.

so could you please suggest something so that it will not pop up the sftp close permission.

I have attached the Pop up msg as image.


So please suggest some solution so that SFTP session will close without asking
Attached Images
File Type: png SFTP disconnect mesg.PNG (8.7 KB, 181 views)

Last edited by jdev; 03-26-2020 at 01:06 PM. Reason: Embed graphics for easier viewing
Reply With Quote
  #6  
Old 03-26-2020, 01:45 PM
jdev's Avatar
jdev jdev is offline
VanDyke Technical Support
 
Join Date: Nov 2003
Location: Albuquerque, NM
Posts: 990
Quote:
Originally Posted by vikram1840 View Post
...but one issue I am facing is before closing the SFTP session it ask from user whether he wants to close the SFTP session or not. So please suggest some solution so that SFTP session will close without asking
You are seeing that message because the Global Option "Show confirm disconnect dialog" is enabled.

Here are two different solutions you can consider implementing:
  • Disconnect the SFTP tab's Session -- objSFTPTab.Session.Disconnect() -- before you call Close().
    This approach is demonstrated in the updated python SFTP Tab Automation example script found in our Example Scripts "Sticky".

    OR...

  • Disable the Show confirm disconnect dialog option located in Global Options > General.
    As of version 8.7 there is now a script API for global options, so this can be turned off from within a script (though you may not desire it to be off for your manual connections), as in:
    crt.Config.SetOption("Show Confirm Disconnect Dialog", False)

--Jake
__________________
Jake Devenport
VanDyke Software
Technical Support
YouTube Channel: https://www.youtube.com/vandykesoftware
Email: support@vandyke.com
Web: https://www.vandyke.com/support
Reply With Quote
  #7  
Old 03-26-2020, 04:22 PM
vikram1840 vikram1840 is offline
Registered User
 
Join Date: May 2019
Posts: 20
Connect Multiple Server Through same script

Hi Jack,

Thank you for your support.
Its all working now.

Thanks a lot.

Regards
Vikram
Reply With Quote
  #8  
Old 03-26-2020, 04:43 PM
vikram1840 vikram1840 is offline
Registered User
 
Join Date: May 2019
Posts: 20
Hi Jack,

Apart from It can you suggest some solution in one more scenario I am having now.
I have some SSH2 connection where SFTP is not accessible by just right click on connected session because port is different for SSH2 connection and SFTP connection.

So in this case is it possible to connect SSH connection and transfer file through SFTP using single script.
Reply With Quote
  #9  
Old 03-26-2020, 05:19 PM
jdev's Avatar
jdev jdev is offline
VanDyke Technical Support
 
Join Date: Nov 2003
Location: Albuquerque, NM
Posts: 990
Quote:
Originally Posted by vikram1840 View Post
Thank you for your support.
Its all working now.
By now we should be getting pretty close to automating almost completely your entire job...


Quote:
Originally Posted by vikram1840 View Post
I have some SSH2 connection where SFTP is not accessible by just right click on connected session because port is different for SSH2 connection and SFTP connection.

So in this case is it possible to connect SSH connection and transfer file through SFTP using single script.
How strange!

SFTP is a subsystem of the SSH2 protocol, so if you have to connect to a different port than you would for the shell connection, I would consider that to be highly unusual and it makes me suspect that in reality it's not an SFTP connection.
  • Are you absolutely 100% positive that in these cases it's an SFTP connection?
  • For these "special" hosts, do you utilize the exact same username and password that to access the shell/terminal as you do to access the SFTP service?
If so, you might be able do something "special" for these "special" hosts.
However, what I have in mind is far too complicated to spend any time on script-wise until it's known whether or not it's even possible with manual execution. Such would need to be vetted by you as follows:
  1. Take one of the sessions you have where the host accepts SSH2 shell/terminal access on the standard port, but requires you to connect to a "special" port for SFTP access...
  2. Copy that session in your Session Manager. Rename the copy to something like: OrigSessionName-SFTP
  3. Edit the SFTP session's properties such that:
  4. The SSH2 category's port is changed to what is required for SFTP access.
  5. In the Port Forwarding category, enable the option at the very bottom named "Do not request a shell"
  6. Save your changes to the SFTP session.
  7. From SecureCRT's File menu, enable Trace Options so that you can see what's happening behind the scenes when you connect to the SFTP sesssion.
  8. Connect to the SFTP session. You should see a bunch of info displayed in the terminal reflecting the behind-the-scenes interaction between SecureCRT and the remote SSH2 (SFTP) server.
    The last lines should reflect RECV : AUTH_SUCCESS as well as "No shell requested".
  9. Now right-click on the tab and choose "Connect SFTP".

    Do you get an SFTP tab successfully established?
If you are able to get successfully connected, *then* we can think about ways to automate this process through scripting; while complicated, it may very well be possible. However, if you can't even get the above manual steps to work the I don't think there's a way to get this done using SecureCRT because of your "special" server not really supporting SFTP connectivity.

--Jake
(vs. Jack; I don't know Jack. )
__________________
Jake Devenport
VanDyke Software
Technical Support
YouTube Channel: https://www.youtube.com/vandykesoftware
Email: support@vandyke.com
Web: https://www.vandyke.com/support
Reply With Quote
  #10  
Old 03-27-2020, 05:53 AM
vikram1840 vikram1840 is offline
Registered User
 
Join Date: May 2019
Posts: 20
Hi Jake,

Yes I am 100% sure that Port of SSH is different from SFTP so cant connect SFTP directly with connected SSH Session.

As You have mentioned steps, I have followed the same and SFTP Session connected successfully.

So can you now please suggest some script to connect SSH connection and SFTP both through same script while having PORT different.


Regards
Vikram
Reply With Quote
  #11  
Old 03-27-2020, 12:32 PM
jdev's Avatar
jdev jdev is offline
VanDyke Technical Support
 
Join Date: Nov 2003
Location: Albuquerque, NM
Posts: 990
After you call ConnectSftp() you want to see whether the connection was successful. You do this by checking the Connected property of the Session object of the SFTP tab. For example:
Code:
objSFTPTab = crt.GetScriptTab().ConnectSftp()

if not objSFTPTab.Session.Connected:
    # Handle this case.
In your scenario, I'd suggest one approach would be to change your sftp_transfer module to return a string that indicates success/fail. For example:
Code:
def sftp_transfer(user_name):
    # crt.Dialog.MessageBox("sftp comes")
    objSFTPTab = crt.GetScriptTab().ConnectSftp()
    if not objSFTPTab.Session.Connected:
        objSFTPTab.Close()
        return "Failure: No SFTP Subsystem"
    .
    .
    .
Then, at the bottom of your ENM() method, you can check for failure and establish a new connection with different parameters. For example:
Code:
    # This used to call sftp_transfer(user_name) alone. Now we're
    # checking its return value for evidence of "Failure:"...
    if "Failure:" in sftp_transfer(user_name):
        crt.Dialog.MessageBox("Failed to connect sftp. Trying alt port...")
        crt.Session.Disconnect()
        # Must be an SFTP only server, let's use alt port and no shell:
        crt.Session.Config.SetOption("[SSH2] Port", 2222)
        crt.Session.Config.SetOption("Request Shell", False)

        # Connect again to the same host, different port, no shell.
        crt.Session.Connect()
        
        # Now that we're connected with the alternate port, do the
        # sftp work...
        if "Failure:" in sftp_transfer(user_name):
            crt.Dialog.MessageBox("OOPS! sftp_transfer() still failed.")

        # Now that we're done with the sftp work with the
        # alternate port, let's restore the default port
        # and shell req for next connection:
        crt.Session.Config.SetOption("[SSH2] Port", 22)
        crt.Session.Config.SetOption("Request Shell", True)
Untested; that's the concept.

--Jake
__________________
Jake Devenport
VanDyke Software
Technical Support
YouTube Channel: https://www.youtube.com/vandykesoftware
Email: support@vandyke.com
Web: https://www.vandyke.com/support
Reply With Quote
  #12  
Old 03-29-2020, 08:04 AM
vikram1840 vikram1840 is offline
Registered User
 
Join Date: May 2019
Posts: 20
Hi Jake,

In suggested code this option not working:

crt.Session.Config.SetOption("Request Shell", False).

I have tried this option with only SFTP part even but that "NO request shell" option didnt get enabled after executing this line.

So could you please suggest any further change in code that can make Request Shell False.

I have tried it manually by enable do not request shell option and then sftp transfer work but when I used this as code it did not work.

So if you can suggest something to enable this Option("Do not request a shell") by code line then my objective will be fulfill.

Regards
Vikram

Last edited by vikram1840; 03-29-2020 at 08:11 AM.
Reply With Quote
  #13  
Old 03-30-2020, 10:11 AM
jdev's Avatar
jdev jdev is offline
VanDyke Technical Support
 
Join Date: Nov 2003
Location: Albuquerque, NM
Posts: 990
Quote:
Originally Posted by vikram1840 View Post
In suggested code this option not working:

crt.Session.Config.SetOption("Request Shell", False)
It's unclear what "not working" looks like, so let's take a step back...

Take the following code and save it to a separate script file.

Code:
#$language = "Python"
#$interface = "1.0"

# ToggleRequestShell.py

curVal = crt.Session.Config.GetOption("Request Shell")
crt.Session.Config.SetOption("Request Shell", not curVal)
newVal = crt.Session.Config.GetOption("Request Shell")
data = "{}\r\n\r\n{}".format(
    "{}".format(crt.Version),
    "Request Shell Mod?\r\n" +
    "     Old: {}\r\n     New: {}\r\n\r\n{}".format(
    curVal, newVal, "(this msg copied to clipboard)"))
crt.Clipboard.Text = data
crt.Dialog.MessageBox(data)
Then, connect to a host (any host).

While connected to the host, run the script.

What is the exact output that the script generates (it will display in a message box and that content will be copied to the clipboard)?

--Jake
__________________
Jake Devenport
VanDyke Software
Technical Support
YouTube Channel: https://www.youtube.com/vandykesoftware
Email: support@vandyke.com
Web: https://www.vandyke.com/support
Reply With Quote
Reply


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT -6. The time now is 01:51 PM.