Jump to content

UDF SSH


JiBe
 Share

Recommended Posts

  Hi to all,

 

 

I only am accustomed pas has posted on the forum (coz, I'm french). But I use it a lot.

So first of all, thank you all to participate in the evolution of this wonderful product.

Today is not one day like any other, I myself am decide has posted a UDF that I myself create and developed (there may be some bug) for some months.

So here it is:

This UDF allows to use the SSH protocol very easily in your code.

It uses the syntax as the TCPxxx() function.

Your code will be easier to convert :-).

 

excused my English, I'm French.

 

Example:

 

#cs ----------------------------------------------------------------------------

AutoIt Version: 3.3.4.0
Author: Joseph Barone 2010-2015

Script Function:
Modele pour l'utilisation de la fonction ssh (plink).

#ce ----------------------------------------------------------------------------

; Script Start - Add your code below here

#include
#include
#include
#include
#include
#include "SSH_udf.au3"

_SSHStartup()

Global $butt[6]

$Gui = GUICreate("SSH Console",550,400)
$label1 = GUICtrlCreateLabel("Adresse IP:",10,10,150,20) ; ip
$input1 = GUICtrlCreateInput("",10,25,150,20) ; ip
$label2 = GUICtrlCreateLabel("Tcp port:",170,10,150,20) ; port
$input2 = GUICtrlCreateInput("",170,25,60,20) ; port
$label6 = GUICtrlCreateLabel("Protocol:",240,10,40,20) ; port
$input6 = GUICtrlCreateInput("ssh",240,25,60,20) ; port
$butt[0] = GUICtrlCreateButton("Connect0",310,5,80,20,$BS_DEFPUSHBUTTON)
$butt[1] = GUICtrlCreateButton("Connect1",390,5,80,20)
$butt[2] = GUICtrlCreateButton("Connect2",470,5,80,20)
$butt[3] = GUICtrlCreateButton("Connect3",310,25,80,20)
$butt[4] = GUICtrlCreateButton("Connect4",390,25,80,20)
$butt[5] = GUICtrlCreateButton("Connect5",470,25,80,20)

$Checkbox = GUICtrlCreateCheckbox("RSA, Fingerprint, Alert AutoValidate", 330, 45, 205, 25)

$label4 = GUICtrlCreateLabel("Login:",10,45,150,20) ; login
$input4 = GUICtrlCreateInput("",10,60,150,20) ; login
$label5 = GUICtrlCreateLabel("Mot de passe:",170,45,150,20) ; password
$input5 = GUICtrlCreateInput("",170,60,150,20,$ES_PASSWORD) ; password

$label3 = GUICtrlCreateLabel("Commande a envoyer:",10,85,150,20) ; send command
$input3 = GUICtrlCreateInput("",10,100,310,20) ; send commande vers l'hote
$butt2 = GUICtrlCreateButton("Send",330,100,80,20,$BS_DEFPUSHBUTTON)
GUICtrlSetState($butt2,$GUI_DISABLE)

$edit = GUICtrlCreateEdit("",10,130,530,260,$WS_VSCROLL);,$WS_DISABLED))

GUISetState()


Global $ConnectedSocket[6] = [-1,-1,-1,-1,-1,-1]
Global $msg, $recv, $ret

; GUI Message Loop
;==============================================
While 1
$nmsg = GUIGetMsg()

If $nmsg = $GUI_EVENT_CLOSE Then ExitLoop

;;; connect part:
$b = 0
While 1
If $nMsg = $butt[$b] Then
If GUICtrlRead($butt[$b]) = "Connect"&$b Then
_SSHParametreSet("yesall",GUICtrlRead($Checkbox))
_SSHParametreSet("protocol",GUICtrlRead($input6))
_SSHParametreSet("login",GUICtrlRead($input4))
_SSHParametreSet("passwd",GUICtrlRead($input5))
$ConnectedSocket[$b] = _SSHConnect(GUICtrlRead($input1),GUICtrlRead($input2))
If $ConnectedSocket[$b] = 0 Then
MsgBox(0,"Erreur", "Impossible de ce connecter!!")
Else
GUICtrlSetData($butt[$b],"Close"&$b
GUICtrlSetState($butt2,$GUI_ENABLE)
EndIf
DisplayArray($_config)
ConsoleWrite("nb config:"&$_nbconf&@CRLF)
Else
_SSHCloseSocket($ConnectedSocket[$b])
GUICtrlSetData($butt[$b],"Connect"&$b
GUICtrlSetState($butt2,$GUI_DISABLE)
DisplayArray($_config)
ConsoleWrite("nb config:"&$_nbconf&@CRLF)
EndIf
EndIf

;;; send part:
If $nMsg = $butt2 Then
$ret = _SSHSend( $ConnectedSocket[$b] , GUICtrlRead($input3)&@crlf)
GUICtrlSetData($input3,"")
GUICtrlSetState($input3,$GUI_FOCUS)
EndIf


;;; receive part:
$recv = _SSHRecv( $ConnectedSocket[$b])
If $recv <> "" Then
GUICtrlSetData($edit, GUICtrlRead($edit) & $recv )
EndIf
GUICtrlSendMsg($edit, $EM_SCROLL, $SB_PAGEDOWN, 0)
$b += 1
If $b = UBound($butt) Then ExitLoop
WEnd

WEnd

_SSHCloseSocket($ConnectedSocket)
_SSHShutdown()

Exit

Func DisplayArray($array)
$i = 0
$j = 0
if UBound($array,1) = 0 Then Return
While 1
ConsoleWrite("(["&UBound($array,1)&"]["&UBound($array,2)&"]) ")
While 1
ConsoleWrite("["&$j&"]"&$array[$i][$j]&" ")
$j += 1
if UBound($array,2)<=$j Then ExitLoop
WEnd
ConsoleWrite(@CRLF)
$i += 1
$j = 0
if UBound($array,1)<=$i Then ExitLoop
WEnd
EndFunc

  

I join with UDF version of modified putty myself.  🙂 LoL

but, it is not used with the UDF, it is included in the UDF.

 

putty-04012015- 92453+lic.zip

ssh_udf.zip

New version (contains the latest version of plink (0.74) edited by http://jakub.kotrla.net/putty/

ssh_udf-v2.zip

Same as the v2 but supports all putty/plink settings

ssh_udf-v2.1.zip

Edited by JiBe
Added code tags
Link to comment
Share on other sites

Thanks for sharing.

mLipok

Signature beginning:
Please remember: "AutoIt"..... *  Wondering who uses AutoIt and what it can be used for ? * Forum Rules *
ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * IE on Windows 11 * How to ask ChatGPT for AutoIt Codefor other useful stuff click the following button:

Spoiler

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST APIErrorLog.au3 UDF - A logging Library * Include Dependency Tree (Tool for analyzing script relations) * Show_Macro_Values.au3 *

 

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

OpenOffice/LibreOffice/XLS Related: WriterDemo.au3 * XLS/MDB from scratch with ADOX

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskSchedulerIE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) * PDF Related:How to get reference to PDF object embeded in IE * IE on Windows 11

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

I also encourage you to check awesome @trancexx code:  * Create COM objects from modules without any demand on user to register anything. * Another COM object registering stuffOnHungApp handlerAvoid "AutoIt Error" message box in unknown errors  * HTML editor

winhttp.au3 related : * https://www.autoitscript.com/forum/topic/206771-winhttpau3-download-problem-youre-speaking-plain-http-to-an-ssl-enabled-server-port/

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2023-04-24

Link to comment
Share on other sites

  • 7 months later...

A nice share, the only question i have:Is there a way to turn off the automatic password responder after logging on?
I have to fill in a secondary password to enable advanced level and this password is not the same as the logon-password.

 

Link to comment
Share on other sites

A nice share, the only question i have:Is there a way to turn off the automatic password responder after logging on?
I have to fill in a secondary password to enable advanced level and this password is not the same as the logon-password.

 

Yes, simply do not fill in the login and password.

Link to comment
Share on other sites

Yes, simply do not fill in the login and password.

I did that, however that unfortunately does not work. After filling in the login data manually, the password will be reused whenever the phrase "Password:" comes back in the buffer. Hence the question how do i toggle off the auto responder completely so that nothing is triggered for that phrase.

login as: Using keyboard-interactive authentication.
Password: 

Router line 2 

Router>enable
Password: 
% Access denied

Router>

 

Link to comment
Share on other sites

Hi lbsl;
 
Your problem is the operation of plink.
_SSHParametreSet ("login", GUICtrlRead ($input4))
_SSHParametreSet ("passwd", GUICtrlRead ($input5))
When you fills both of these parameters, plink will parsed messages login and password and answer. It cannot be the prevented.

 

to avoid the problem, should you send from the code the login and the password.

 

viewing I modified the example so that plink manages more authentication.
 
excuse my English, I'm French!

ssh2.au3

Link to comment
Share on other sites

  • 1 year later...

Hi Chamlien,

It can, but it's a little more difficult to set up :-)

 

Single Port Redirerction

$__PortForwardings = "L8080=192.168.0.200:80"

 
Dynamic port forwarding (used for example with Proxifier)

$__PortForwardings = "D3128="

Edited by JiBe
Link to comment
Share on other sites

  • 2 years later...
  • 8 months later...

Thanks for the UDF. It has really helped me implement an SSH interface with my modem very quickly. My previous code used TelNet and the SSH UDF seems so much more secure.

I have a question:

My router responds really slowly to _SSHConnect(). It returns a non-zero channel number quickly but the following _SSHRecv() function does not detect a prompt for several seconds. This is usually 4 to 6 seconds but could be over 30 seconds. I use a timer to abandon the attempt to communicate at 30 seconds.

Several suggestions point to this being an issue with 'ReverseDNS' and suggest setting some options, for example 'UseDNS no'. Where are these stored in the UDF?

I am trying to extract line performance statistics from the modem every five minutes and have the AutoIT program set as a scheduled windows task. Would I be better setting up a channel and leaving it open - then calling for the log every five minutes?

Any help gratefully received. 

 

Thanks

John

; Start the service and register OnAutoItExit to be called when the script is closed, to ensure that the session is closed correctly.
_Log("Opening Communications")
_SSHStartup()
OnAutoItExitRegister("OnAutoItExit")

;Connect to modem/router telnet port
_Log("Connecting")
Local $hTimer = TimerInit()
Local $RouterIP = _SSHConnect($DeviceIP, "22", $DeviceUserName, $DevicePassword)

;Check that modem/router is responding
If $RouterIP = 0 Then
    $Connected = "No"
    _Log("Failed to connect")
Else
    $Connected = "Yes"
    _Log("Connected: (" & $RouterIP & ")")

;    Wait for prompt
    $i = 0
    _SSHSend($RouterIP, "" & @CRLF)
    Do
        Sleep(1000)
        $TCPRecv = _SSHRecv($RouterIP, "5000")
        FileWriteLine($DlyFilename, @MDAY & "/" & @MON & "/" & @YEAR & " " & @HOUR & ":" & @MIN & ":" & @SEC & "." & @MSEC & ";" & $TCPRecv )
        _Log($TCPRecv)
        $i = $i + 1
    Until StringInStr($TCPRecv,">") > 0 OR $i = 30 

    If StringInStr($TCPRecv,">") > 0 Then
        $LoggedIn = "Yes"
        _Log("Logged in at " & $i & " seconds.")

;        Send WAN SHOW command
        Sleep(1000)
        _SSHSend($RouterIP, "wan show" & @CRLF)
        Sleep(100)
        $TCPRecv = _SSHRecv($RouterIP, "5000")

..etc

        EndIf
    Else
        $LoggedIn = "No"
        _Log("Responding, but too slow in accepting login. Gave up at " & $i & " seconds.")
    EndIf

   _ProcessStats()

EndIf

_SSHCloseSocket($RouterIP)
_SSHShutDown()

 

Edited by Melba23
Added code tags
Link to comment
Share on other sites

  • Moderators

g0gcd,

Welcome to the AutoIt forums. When you post code in future please use Code tags - see here how to do it.  Then you get a scrolling box and syntax colouring as you can see above now I have added the tags. Thanks in advance for your cooperation.

M23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites


Hi g0gcd,

Yes, I found this connection time from 4 to 5 sec.
I have never made the connection with a DNS resolution deadline.
For me, this deadline is SSH trading time
Maybe I'm wrong. 
However, if you know the putty/plink setting to prevent DNS resolution, 

You can overload plink settings using the _SSHParametreSet ($_NameParameter, $_Value) feature
Before calling the function _SSHConnect ($_IPAddr, $_port -22, $_login , "", $_passwd - "")

Just for the record, I have not updated this UDF.
In the state, it uses an old version of plink.
It contains flaws that have not been fixed, so take precautions.

I didn't update it, because I would have to adapt the changes to the original Putty/plink code.
And I don't have too much time for that. Also, I feel that AutoIT is a bit finished, there is no new version for a long time.

In terms of the added options, there are two.
1 - the ability to autologin with the password hidden in the spot manager.
2 - the ability to respond yes automatically to new connections.

I hope I understand your question and answered it correctly.


PS: I hope my English is readable, I'm French. 
Jibe

Link to comment
Share on other sites

Melba23,

Apologies, brain fade. To mis-paraphrase your tagline "I'm old too!"

Thanks for correcting it for me.

Jibe

Thank you for responding very quickly. I have now pinned down the problem to my modem/router not having a matching cipher (not the reverse DNS issue that I thought it was). I need to adjust the connect string to get something like: ssh -c 3des-cbc admin@192.168.1.254. This works using OpenSSH and PuTTY; I just need to figure out where to tweak the parameter set in the UDF to get the cipher definition inserted. I currently have PuTTY and PLink references open and will look more deeply into _SSHParametreSet().

I understand your comments about AutoIT. It's an extremely useful tool and it's probably as near perfect as it can get, so I'm not surprised that it's not been revised recently.  Thank you once again for solving 95% of my problem. You have saved me a lot of time.

I may just take the time to update the embedded PLink version, as that may help someone else in the future. I can see how you've done that and, if I get around to it, I'll mail the revised code block for you to patch in.

Aussi,

Votre langue anglaise est bien meilleure que mon français! Je n'ai aucun problème à te comprendre.

Best wishes

John

G0GCD

 

 

Link to comment
Share on other sites

Hi g0gcd,

for your need for a connection chain, I added in the v2.1 all the parameters accessible via Plink/Putty.

For your use, I think you should get back the putty edition that I site. Make your setup with putty and save it. you will have a sessions directory in which your session is backed up, this will give you the settings used with _SSHParametreSet()

http://jakub.kotrla.net/putty/portable_putty_074_0.16.0_all_in_one.zip

Example:

_SSHParametreSet("HostKey", "ed25519,ecdsa,rsa,dsa,WARN")
_SSHParametreSet("KEX", "ecdh,dh-gex-sha1,dh-group14-sha1,rsa,WARN,dh-group1-sha1")
_SSHParametreSet("Cipher", "aes,chacha20,3des,WARN,des,blowfish,arcfour")

for English, thank you Bing Trad 🙂

JiBe

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...