В операционных системах семейства Linux для удаленного доступа между машинами широко используется протокол SSH. Его популярность обусловлена простотой, надежностью и безопасностью соединения. Подключившись по SSH к удаленному компьютеру, вы получаете возможность выполнять на нем любые команды терминала, как будто вы работате на своем компьютере, работает даже автодополение и другие вспомогательные возможности.
Иногда возникает необходимость подключиться к удаленному компьютеру Linux из Windows, но по умолчанию, там нет утилиты предназначенной для этого. Есть сторонняя программа, она называется PuTTY и вы можете установить ее отдельно. В этой статье мы рассмотрим как пользоваться PuTTY для подключения к Linux системам, а также поговорим как выполняется настройка PuTTY для удобного использования.
Содержание статьи
- Установка PuTTY
- Как пользоваться PuTTY
- Выводы
Сначала нужно скачать установщик программы. Для этого откройте официальный сайт и нажмите «You can download PuTTY here»:
Затем выберите установщик для вашей архитектуры, x86 или x64 и загрузите его.
На первом шаге нажмите «Next»:
Папку для установки можно оставить по умолчанию:
Компоненты тоже:
Дождитесь завершения установки:
Снимите галочку с «View README» и нажмите «Finish»:
Теперь перейдем к тому как выполняется работа в PuTTY.
Как пользоваться PuTTY
1. Интерфейс программы
Сразу же после запуска программы из меню пуск вы увидите графический интерфейс ее настройки. После подключения вы будете видеть только терминал, но настроить программу можно через удобный интерфейс.
Рассмотрим за что отвечают те или иные вкладки программы, чтобы вы ориентировались что и где искать. У нас есть четыре вкладки:
- Session — отвечает за подключение удаленному серверу, тут мы вводим параметры подключения, порт, адрес, а также можем сохранить все настройки putty, чтобы не настраивать каждый раз заново.
- Terminal — позволяет включать или отключать возможности терминала;
- Window — настройка внешнего вида окна, цвет, шрифт, кодировка;
- Connection — настройка параметров подключения, алгоритма шифрования, сжатия, ключей аутентификации, X11 и других параметров.
Каждая вкладка имеет несколько подразделов, но мы не будем сейчас их трогать, а перейдем сразу к практике и посмотрим как подключиться putty к удаленному узлу.
2. Подключение к удаленному компьютеру PuTTY
Чтобы подключиться к удаленному компьютеру по SSH перейдите на вкладку «Session», здесь, в поле «Host Name» необходимо прописать ip адрес или имя хоста, компьютера, к которому вы хотите подключиться, в поле порт — нужно указать порт, на котором запущен SSH сервер, по умолчанию используется порт 22:
Далее, нажмите кнопку «Open». После этого появится запрос на добавление ключа сервера в список доверенных ключей, нажмите «Да»:
Затем вам будет нужно ввести логин пользователя и пароль. Важно заметить, что скопировать логин или пароль у вас не получится, необходимо только вводить вручную:
Теперь авторизация прошла успешно, и вы можете выполнять нужные действия на сервере:
3. Сохранение сессии PuTTY
Чтобы не вводить каждый раз ip и порт можно сохранить эти данные в виде сессии, для этого пропишите новое имя в поле «Saved Sessions», а затем нажмите кнопку «Save»:
Теперь вы сможете загрузить сохраненную сессию, нажав кнопку «Load».
После того как будет завершена настройка putty и все параметры будут выставлены правильно вы можете сохранить настройки и не вводить их несколько раз.
4. Имя пользователя по умолчанию
Вы можете не вводить имя пользователя каждый раз, для этого перейдите на влкадку «Connection», затем «Data» и в поле «Auto-login Username» пропишите имя пользователя, например, root:
Теперь подключение putty будет выполняться от имени этого пользователя.
5. Авторизация по ключу ssh в PuTTY
Чтобы не вводить каждый раз пароль можно настроить авторизацию по ключу. В Linux такая возможность используется очень широко потому что это удобно. Первым делом необходимо создать ключ. Для этого запустите утилиту PuTTYgen и установите переключатель в положение «SSH-2 RSA» нажмите «Generate»:
Обязательно ключ должен быть SSH-2 RSA, если в главном окне нет, выберите в меню «Key». Подвигайте мышкой, чтобы создать достаточное количество энтропии:
Ключ готов, затем, с помощью кнопок «Save Public Key» и «Save Private Key» сохраните оба ключа.
Далее, откройте PuTTY, перейдите на вкладку «Connection», затем «SSH», затем «Auth»:
Здесь необходимо нажать кнопку «Browse» и добавить недавно сохраненный приватный ключ:
Далее, возвращаемся на вкладку «Session», выбираем наше сохранение и нажимаем «Save» чтобы сохранить настройки. Осталось только отправить наш открытый ключ на сервер. Для этого авторизуйтесь на нем с помощью пароля и открытый ключ вставьте ключ в конец файла /root/.ssh/authorized_keys.
Ключ можно брать прямо из окна PuTTYgen «Public key for pasting» или из файла открытого ключа:
Все, теперь можно выходить и авторизоваться снова. На этот раз подключение по ssh putty будет выполняться с помощью нашего ключа. Не забывайте сохранять настройки сессии, чтобы не выбирать ключ каждый раз. Теперь вы знаете как пользоваться программой putty, рассмотрим еще передачу файлов.
5. Передача файлов через scp в PuTTY
Не все знают, но PuTTY позволяет передавать файлы через ssh также как это делает linux с помощью утилиты scp. Нажмите Win+R, затем пропишите cmd, чтобы запустить командную строку.
Синтаксис утилиты pcsp выглядит следующим образом:
pscp опции путь_файлу имя_пользователя@хост:/путь/к/файлу/на/удаленном/хосте
Например, мы можем отправить файл из текущей папки в папку пользователя /root/:
pscp test.txt root@185.22.173.108:/root/
С помощью опции -P можно задать удаленный порт:
pscp -P 2250 test.txt root@185.22.173.108:/root/
А опция load позволяет загрузить сохраенные настройки сессии PuTTY:
pscp -load losst-2 test.txt root@185.22.173.108:/root/
Теперь вы знаете как использовать putty для передачи файлов.
Выводы
В этой статье мы рассмотрели как пользоваться PuTTY для решения задач администрирования Linux в Windows. Иногда случаются ситуации, что без ssh в windows никуда, тогда эта утилита будет просто незаменимой.
Believe it or not, Secure Shell (SSH) is becoming one of the most important remote connection protocols today.
Here is our list of the best SSH clients for Windows:
- Solar-PuTTY – EDITOR’S CHOICE – FREE TOOL This free tool, provided by SolarWinds, that builds on the functionality of the original PuTTY. This system offers a better interface that integrates file transfers with SFTP as well as SCP. The interface connects to remote computers with SSH and Telnet. Download 100% free tool.
- PuTTY This very old terminal emulator is an inspiration for all subsequent remote access systems. This tool offers Telnet, SSH, Rlogin, and raw socket connections plus SFTP and SCP for file transfers.
- SecureCRT This remote access system is available for macOS, Linux, and iOS as well as Windows. It offers terminal emulation and file transfer through an SSH tunnel.
- SmarTTY A free SSH client that has a multi-tabbed interface to allow multiple simultaneous connections. This tool also includes SCP capabilities for file transfers.
- mRemoteNG This popular, free remote desktop system includes a tabbed interface for multiple simultaneous connections. The system offers access with RDP, Telnet, Rlogin, VNC, and SSH.
- MobaXterm This easy-to-use remote access system is available in free and paid versions and is built for Unix and Linux, and well as Windows. The tool SSH and SFTP.
SSH is used by many systems and network administrators to connect to their remote cloud computing resources. It can help them create an SSH tunnel and solve problems while avoiding putting the resources at risk.
The SSH client is the key element to providing this secure and flexible SSH tunnel connection to any remote resource. It provides access through the command line of the remote resource and lets you execute any command to monitor or fix issues.
There are many SSH clients available for free, but most of them do not fulfill the standards for serious everyday users. We’ll go over the Top SSH clients for Windows in the following list and show all the different options and flexibility they have.
It all depends on what you need, but going with one or the other will certainly give you a good head start.
The Best SSH Clients for Windows
Our methodology for selecting secure SSH clients
We reviewed the market for SSH clients for Windows that enable session and password saving and analyzed the tools based on the following criteria:
- A secure remote terminal utility
- An encrypted password storage system
- A system for storing connection settings to enable point-and-click immediate contact
- The ability to maintain multiple sessions open
- Session pause and resume functions
- A free trial or a free tool
- A free tool that is worth using or a paid tool that offers value for money
With these selection criteria in mind, we located a range of options for secure SSH clients that are written for Windows.
1. SolarPuTTY – FREE TOOL
SolarPuTTY is a 100% free SSH client for Windows, developed by SolarWinds. Although SolarPuTTY carries the name PuTTY, it does a lot more than just open SSH sessions to remote devices. It also supports SCP, SFTP, and Telnet and comes with additional features.
Key Features:
- Multi-Session Tabs: Open and manage multiple sessions in one window.
- Automatic Reconnection: Resumes sessions after interruptions.
- Credential Storage: Securely saves login details for quick access.
- Color-Coded Sessions: Easily organize and identify multiple connections.
- Script Automation: Execute post-connection scripts efficiently.
Unique Feature
One distinctive feature of SolarPuTTY is its ability to establish multiple sessions within a single console. It has a tabbed interface that lets you open multiple sessions in one window, making it more efficient than traditional PuTTY.
Why do we recommend it?
While reviewing SolarPuTTY, we found this SSH client to be exceptionally efficient and easy to use. Its graphical user interface and the ability to open multiple tabs for multi-session use, streamlined our access to SSH and Telnet, surpassing the standard PuTTY.
SolarPuTTY integrated a modern interface that is easy to use. This interface lets you work on simultaneous sessions through its multi-tabbed single console, and allows you quick access to previous sessions. But one of the best and most popular features is its tabbed interface.
With PuTTY, you had to open the interface multiple times, and swap between applications which made it difficult to navigate through. But the SolarPuTTY can establish multiple sessions within the same console and lets you switch back and forth between them.
The homepage includes quick access “Single-click” logging of each session with saved credentials and private keys.
Who is it recommended for?
Solar-PuTTY is highly recommended for system engineers and network administrators, particularly those working in Windows environments.
Pros:
- User-Friendly Interface: Offers an intuitive and modern interface for efficient management of multiple sessions.
- Secure Credential Handling: Stores credentials and private keys securely for hassle-free logins.
- Efficient Session Management: Tabs and color-coding aid in organizing simultaneous connections.
- Scripting Support: Enhances functionality with script automation capabilities.
Cons:
- Technical Knowledge Required: May be challenging for users without basic networking knowledge.
SolarPuTTY is free.
EDITOR’S CHOICE
Solar-PuTTY is our top pick for an SSH client on Windows because it is a reliable tool that offers both SSH and Telnet connections and best of all, it is completely free to use. This free system allows you to store login credentials securely and if your connection gets dropped mid-session, the service will automatically re-establish your session. This is a secure, efficient, and trust-worthy tool with a tabbed interface that lets you work on multiple sessions simultaneously.
Download: Start 30-day Free Trial
OS: Windows Server
Related Post: What Is SFTP?
2. PuTTY
PuTTY is one of the more popular and widely used SSH clients for Windows platforms. This lightweight, free, and open-source terminal emulator, can be found in all network and systems administrator toolboxes. It is easy to use and can support multiple network protocols such as SSH, Serial, Telnet, SCP, SFTP, Rlogin, and Raw Socket connections.
Key Features:
- SSH Key Management: Efficiently handles SSH encryption keys.
- IPv6 Support: Compatible with modern internet protocols.
- Serial Port Connections: Facilitates connections to local serial ports.
- Public-Key Authentication: Offers enhanced security features.
- Simple Interface: Easy-to-use interface for basic SSH connections.
Why do we recommend it?
After using this SSH client, side-by-side with others, we found it to be significantly easier to set up and use than others. PuTTY is simple yet efficient for providing basic and secure remote access to networked devices. But, while PuTTY is great in providing secure SSH connections, it may be less suitable for advanced functionalities like file transfers.
Preferably, PuTTY is used as a way to establish remote shell access to UNIX or Linux-based endpoints like network devices, servers, systems, virtual machines, etc. It provides you with a text user interface to these remote end systems. It is also often used as a serial console application, as it can be configured to open serial connections.
PuTTY is an agile application. It can let you save session configuration, session logging, proxy settings, and screen customizations.
PuTTY is a very basic tool. Although it provides what it promises, “a secure SSH connection,” it lacks additional functionality.
Who is it recommended for?
PuTTY is recommended for anyone, from home users with no technical expertise to network and systems administrators. It is for anyone (Windows or Linux users) who primarily needs to establish secure shell access to UNIX or Linux-based endpoints.
Pros:
- High Popularity: Widely recognized and trusted in the industry.
- Open-Source Advantage: Free and continuously improved by the community.
- Comprehensive Protocol Support: Supports a variety of network protocols.
- Basic Functionality Focus: Ideal for simple, secure SSH connections.
Cons:
- Limited Advanced Features: Lacks more sophisticated functionalities like integrated file transfer.
PuTTY is free.
To discover more comprehensive SSH clients for Windows, keep reading.
3. SecureCRT
SecureCRT by VanDyke Software, is another popular SSH, Telnet client, and terminal emulator for Windows systems. The main difference with previous tools is that SecureCRT is offered over a commercial license.
Key Features:
- Advanced Session Management: Exceptionally manages multiple sessions.
- Scripting Capabilities: Automate tasks with robust scripting features.
- Cross-Platform Availability: Compatible with Windows, Mac, and Linux.
- Color Schemes Customization: Personalize workspace appearance.
- Tab Grouping: Organize sessions efficiently with tab groups.
Unique Feature
The most distinctive feature of SecureCRT is its robust scripting and automation capabilities. This allows users to record and save scripts, enabling automation of tasks across multiple devices.
Why do we recommend it?
SecureCRT is amazing! While comparing it side-by-side with others, we found several key features that make it stand out as one of the best SSH clients for Windows. We found SecureCRT to have one of the best session management capabilities, plus, it includes other powerful features like scripting and automation, high-security standards, stable and reliable performance, and a user-friendly interface.
But being commercial has tons of advantages, for example, their tool is also supported by macOS and Linux systems, and their tech support can help you resolve issues related to the software.
Out-of-the-box, SecureCRT has tons of functionalities. For example, similar to SolarPuTTY, you can access and manage different remote sites from a single place. It also comes with the “quick connect option” that lets you connect to previous sessions without any additional configuration.
SecureCRT supports various remote protocols as well, including SSH1, SSH2, Telnet, Telnet/TLS Rlogin, Serial, and TAPI.
Who is it recommended for?
Although anyone could use SecureCRT, as it is quite user-friendly, SecureCRT is more recommended for IT and network pros. Additionally, since it is not free, SecureCRT is more recommended for organizations that prioritize advanced functionalities and automation, and require cross-platform compatibility.
Pros:
- Robust Automation Tools: Offers powerful scripting and automation options.
- High-Security Standards: Ensures secure remote access and data tunneling.
- User-Friendly Design: Intuitive interface for easy navigation.
- Multi-Platform Support: Available for various operating systems.
Cons:
- Outdated Interface: The interface can feel somewhat dated and clunky.
For one SecureRT license, the price starts at $99.00 with one year of updates. SecureCRT is supported by Windows, MacOS, and Linux. For Windows, it comes in two versions, the 64-bit, and 32-bit Windows PC Installer. You can download a free trial version of SecureCRT.
4. SmarTTY
SmarTTY is another free multi-tabbed SSH client with SCP support for Windows. As most tools mentioned in this list, SmarTTY can also replace PuTTY’s functionality. You can open multiple tabs for a single SSH sub-session, and also copy files and directories with SCP file transfer protocol.
Key Features:
- File Operations: Seamless file transfer and editing capabilities.
- Smart Terminal: Advanced terminal with auto-completion.
- COM Ports Support: Built-in terminal functionality for COM ports.
- Public Key Authentication: Enhances security with public key methods.
- Graphics Support: Includes built-in Xming for graphical operations.
Unique Feature
A unique feature of SmarTTY is its native Windows file editing and conversion capabilities, which ensure familiar editing and consistent formatting across operating systems.
Why do we recommend it?
While using SmarTTY for a while, we found several compelling reasons to recommend it. For instance, this SSH client provides a multi-tabbed interface and also comes with a Smart Terminal. But if that is not enough, SmarTTY features a Windows-style GUI (for those Windows users), has built-in efficient file editing and conversion, and supports recursive SCP and TAR.
SmarTTY is updated frequently. Their latest SmarTTY version 3.0 provides new functionalities such as the Smart Terminal with auto-completion, a file panel, and a package management GUI.
Who is it recommended for?
SmarTTY is recommended for the ordinary Windows-environment users who need to manage multiple SSH sessions and need seamless file operations. It’s especially good for people who are looking for a tool that can do more than PuTTY.
Pros:
- Extended SSH Terminal Emulation: Offers advanced features beyond basic SSH.
- Multiple Sessions Support: Efficient management of simultaneous sessions.
- Intuitive File Transfers: Streamlines SCP file transfer process.
- Windows Exclusive: Limited to Windows operating systems.
Cons:
- Learning Curve: May require time to fully utilize its advanced features.
Get SmarTTY client for Windows for free from their official site.
5. mRemoteNG
mRemoteNG is a fork of the open-source and remote connections manager, mRemote. mRemoteNG or mRemote Next Generation is also open source, but they fixed bugs and included new features to the traditional mRemote.
Key Features:
- Connection Sharing: Import, export, and share connection setups.
- Tabbed Interface: Manage multiple sessions via tabs.
- Organizational Tools: Use folders and icons for connection organization.
- Inherited Properties: Simplify setup with folder property inheritance.
- Protocol Variety: Supports SSH, RDP, VNC, and more.
Why do we recommend it?
Throughout our testing and evaluation, mRemoteNG proved to be a commendable tool for managing remote connections. We found this tool to be ideal for its efficient tabbed interface (for remote desktops), support for multiple protocols, ease of organization, and configurability.
Similar to SolarPuTTy, the mRemoteNG interface allows you to view all your remote simultaneous connections from a single tabbed interface. Of course, mRemoteNG supports SSH connections, but you can also connect through RDP, VNC, ICA, Telnet, HTTP/HTTPS, Rlogin, and Raw Sockets Connections. mRemoteNG can also store credentials, something not possible with traditional PuTTY.
Who is it recommended for?
mRemoteNG is ideal for IT professionals managing multiple servers and diverse remote connections. It is also perfect for IT teams collaborating on infrastructure setups.
Pros:
- Open-Source Community Support: Actively developed and improved.
- Lightweight GUI: User-friendly interface for managing connections.
- Multi-Protocol Support: Compatible with various remote protocols.
- Credential Storage: Securely saves login information for repeated use.
Cons:
- Crowded Interface: Can become cluttered with numerous connections.
mRemoteNG is free from its official website.
6. MobaXterm
MobaXterm is another tabbed SSH client for Windows systems. It is a popular terminal among systems and network admins that want to access UNIX-based systems, like AIX, HP-UX, Solaris, etc., and Linux (Ubuntu, RedHat, etc), from Windows. MobaXterm is also another improved version of the traditional PuTTY. Aside from fully supporting SSH, it also supports other remote protocols such as VNC, RDP, XDMCP, Telnet, rlogin, FTP, SFTP, etc.
MobaXterm provides similar features such as previous tools, but it includes a couple of unique functionalities.
For example, MobaXterm includes the embedded X Server based on X.org., which allows remote applications to be displayed on the Windows computer.
Key Features:
- X-11 Forwarding: Efficiently handles remote application displays.
- Plugin Extensions: Expand functionality with additional plugins.
- Encrypted File Transfers: Secure SFTP/FTP support.
- SSH Gateway: Simplifies complex SSH connections.
- SSH Tunnels: Facilitates port forwarding for enhanced security.
Unique Feature
MobaXterm’s distinctive feature is its embedded X Server, which enables remote applications to be displayed on the Windows computer. It is also worth mentioning MobaXTerm’s comprehensive CLI toolset.
Why do we recommend it?
While actively testing and exploring MobaXTerm, we came up with various reasons to recommend it. For instance, it provides support not only for SSH, but also for other remote protocols like VNC, RDP, and even FTP.
This tool makes it easy to navigate through UNIX servers through your Windows systems. It provides basic UNIX commands and tools like PS, AWK, Bash, find, and more. It can highlight syntax and use different colors on specific keywords. In fact, most systems admins have replaced the popular CygWin for MobaXterm.
Who is it recommended for?
MobaXterm is recommended for systems and network administrators who access UNIX-based systems from Windows frequently. To maximize its usage, MobaXterm is most suitable for advanced users, particularly for those looking for advanced functionalities like X-11 forwarding and extended protocol support.
Pros:
- Linux/Unix System Accessibility: Ideal for accessing UNIX systems from Windows.
- Simple Learning Curve: User-friendly for new and experienced users.
- Extensive Protocol Support: Facilitates a variety of remote connections.
- Advanced Forwarding Options: Provides X-11 forwarding for demanding users.
Cons:
- Pro Version Costs: Additional features require purchasing the Pro version.
The MobaXterm Home Edition is free, and the Professional Edition starts at $69 per user. Download the MobaXterm Home Edition for free or subscribe to try the MobaXterm Professional Edition.
Final Words & Conclusion
If you are looking for a good SSH client for Windows, you don’t have to search anymore. Any of the tools shown in this list can provide you with secured SSH tunnels at a decent price, and in most cases, for free.
One of the preferred features, found in the new SSH clients, of many system admins is the ability to use multiple tabs to work with simultaneous SSH connections. Admins also love to have the ability to save credentials and use quick access to remote connections. Unfortunately, these are features not available in the common PuTTY.
Although PuTTY is still the number one in popularity in this list, things are changing. There are many far superior new tools out there, such as SolarPuTTY which lets you save the most frequently used sessions, and also export/import settings and share with other team members.
Windows SSH Clients for Managing/Saving Passwords FAQs
How does an SSH client secure the connection to a remote server?
An SSH client secures the connection to a remote server by encrypting all data transmitted over the connection.
What is the default port for SSH connections?
The default port for SSH connections is 22.
Can an SSH client be used to transfer files between a local and a remote machine?
Yes, an SSH client can be used to transfer files between a local and a remote machine using protocols such as SCP (Secure Copy) or SFTP (SSH File Transfer Protocol).
How does an SSH client handle authentication when connecting to a remote server?
An SSH client typically uses either password authentication or public key authentication to handle authentication when connecting to a remote server.
How does an SSH client differ from an SSH server?
An SSH client is used to initiate connections to remote servers, while an SSH server is installed on a remote machine to allow incoming connections.
One of the major advatanage of developing server side applications in your local enviornment is that the terminal session never gets disconnected. The session is always available.
1 2 3 4 5 6 7 8 |
➜ yywe.github.io git:(master) ✗ ls Gemfile _javascript assets Gemfile.lock _layouts gulpfile.js LICENSE _plugins index.html README.md _posts jekyll-theme-chirpy.gemspec _config.yml _sass note.txt _data _site package.json _includes _tabs tools |
However, in many companies, it is daily work to SSH into a server and do the development work, and it is annoying that you often see that your session session get disconnected.
1 |
client_loop: send disconnect: Broken pipe |
This may happen while you are having launch or due to network issue or other whatever reason. The consequence is that your onging work/process will be terminated due to this closed session.
To solve the problem, I have known the “screen” command for a long time, which can decouple the server side processes with the console window. However, it is still normal that you SSH session may be disconnected and you need to re-connect and attach the your screen session.
Is there any way to make your SSH session in a remote server never gets lost and work like your local terminal session. Probably yes! In this post, I will introduce how to achieve this goal. The basic idea is to combine “autossh” and “screen”.
If you are not familar with autossh and screen, you might want to learn some basics before continue reading. Usually screen is already installed in the remote server, and you need to install autossh in your local machine.
Let’s make your remote SSH session like your local terminal session and never gets lost!
1. Prepare your screen config.
This is simple, vim ~/.screenrc and put below line:
1 |
termcapinfo xterm* ti@:te@
|
in the file. If you do not do this, when you scroll your mouse wheel you cannot view your historical commands and output.
2. Write the below shell script to a file like myssh.sh
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
# get your local terminal session id (macos, other platform not verified) session_id=$(echo $TERM_SESSION_ID | cut -d':' -f2) # set your username user_id=<username> # the host you will be connecting, will be passed as a parameter host=$1 if [ -z $host ]; then echo "please specify the host" exit fi echo "autossh connect to $host using sessionid=$session_id" # key command, explanation will be followed. autossh -M 0 -o TCPKeepAlive=yes -o ServerAliveCountMax=20 -o ServerAliveInterval=30 $user_id@$host -t screen -d -R $session_id |
Explanation
-
-M 0: you can specify autossh to open extra TCP port to monitor your ssh session, but in practice I find that is not a must, can use -M 0 so we do not open extra ports in your server.
-
-o TCPKeepAlive=yes -o ServerAliveCountMax=20 -o ServerAliveInterval=30 : This is the first layer of protection, the options specified here will try to keep your SSH session alive by sending heartbeat information at given interval. This is optional as we will have another two mechanism to make your session persistant.
- screen -d -R $session_id: -R $session_id will try to attach to a screen session named $session_id if exists, if not exists, it will create a session named $session_id. However, it may happen that one ssh connection is disconnected but the server is not refreshed (detached), when autossh reconnect, since it is still attached, it will start a new screen session with different process id and you will end up like below:
1 2
4028118.4A435FE8-E9D4-42E8-A40F-FCCFF5C198C2 (07/29/2023 01:13:37 AM) (Attached) 3802470.4A435FE8-E9D4-42E8-A40F-FCCFF5C198C2 (07/28/2023 05:43:22 PM) (Detached)
you will have 2 processes using the same session id! That is why -d comes into the picture. with -d, it will first detach any existing one first. So you will eventually have 1 session binded to your local terminal window.
- now your session will be under the protection of screen, so you will never lose your session context. Lastly, if for whatever reason like network issue, your connection get lost, autossh will reconnect and reattach to the dedicated screen session.
3. Usage
with the above script, if you want to ssh into your remote server, do:
1 |
~/myssh.sh myserver.mydomain.com
|
4. Tips
Now you will have your SSH session persisted, and you will never (hopefully) have your SSH session disconnected unexpectedly. However, if you closed your terminal window, your screen session may still be there. So you may need to constantly monior your screen sessions. Put below lines in your server’s ~/.bashrc
1 2 3 4 5 6 7 8 9 |
alias sls='screen -ls' function sk(){ sname=$1 if [ -z $sname ]; then echo "require session name" return fi screen -S $sname -X quit } |
With the setting, you can use sls
to list existing screen sessions. If you do not want any of them, do sk session_name
to quit the session.
Now you are enpowered to use your remote server like they are your local machine without need to worry about the annoying disconnection issue.
Привет!
Активно работаю с удаленными Linux серверами через Putty и столкнулся с такой проблемой — после того как меняю сеть — все коннекты отваливаются и приходится снова активировать сессии. На данный момент немного упростил процесс через screen и автологин, но вот так чтобы привязать конкретное окно Putty к сессии — пока нет идей как организовать.
Кто-нить решал такую задачку уже или нужно свой лисапед делать?
-
Вопрос задан
-
3952 просмотра
Пригласить эксперта
Все логично.
Тут дело не в ssh, а в tcp поверх которого уже работает ssh. При смене IP-адреса (сети) рвется tcp-соединение. А новое соединение требует уже нового хендшейка и т.д.
То-есть, Вам нужно, чтобы в случае разрыва программа заново подключалась к Вашему серверу, а это значит проходила авторизацию и еще запускала нужный на сервере screen.
Готового решения подобного под windows, к сожалению, не видел.
Нашел решение — немного модифицировал исходники Putty и теперь он при запуске генерирует специальный ключ и передает его на сервер при коннекте и таким образом связывается конкретная сессия screen и Putty
Войдите, чтобы написать ответ
-
Показать ещё
Загружается…
Минуточку внимания
- Подготовка к сохранению сессии соединения с сервером в PuTTY
- Настройка сессии соединения с сервером в PuTTY
- Список сохранённых сессий PuTTY
- Как сохранить сессию соединения с сервером в PuTTY.
Разобравшись, как зайти с помощью PuTTY на сервер по протоколу SSH, хочется большего. А конкретно, не вводить каждый раз имя сервера, с которым в данный момент возникло желание поработать, не выбирать протокол соединения, и, вообще, как можно меньше вводить и как можно быстрее получать результат! Это нормальное желание и разработчики PuTTY об этом позаботились. Есть возможность сохранять сессии соединения с разными серверами.
Настройка сессии соединения с сервером в PuTTY.
Для того, чтобы сохранить сессию соединения с сервером в PuTTY нужно открыть PuTTY, ввести имя сервера (или его IP), выбрать протокол соединения (порт определится автоматически, но, если он не совпадает, можно поправить вручную), после этого в поле «Saved Sessions» следует ввести название сессии.
Это важный момент, т.к. даже с одним и тем же сервером можно коннектиться под разными пользователями (для чего это понадобится, будет понятно позже, когда пойдёт речь, как сохранять ещё и логин с паролем
).
После того, как название сессии введено, следует нажать на кнопку «Save»:
Список сохранённых сессий PuTTY.
Сразу после этого сессия попадёт в список сохранённых сессий и её там всегда можно будет найти (если её не удалять, но это другая история). =)
Как сохранить сессию соединения с сервером в PuTTY
Заберите ссылку на статью к себе, чтобы потом легко её найти!
Раз уж досюда дочитали, то может может есть желание рассказать об этом месте своим друзьям, знакомым и просто мимо проходящим?
Не надо себя сдерживать!