<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>automation - Hard Wired</title>
	<atom:link href="https://www.hardwired.dev/tag/automation/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.hardwired.dev</link>
	<description></description>
	<lastBuildDate>Wed, 25 Sep 2024 12:11:43 +0000</lastBuildDate>
	<language>cs</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9</generator>

<image>
	<url>https://www.hardwired.dev/wp-content/uploads/2022/10/android-chrome-256x256-1-150x150.png</url>
	<title>automation - Hard Wired</title>
	<link>https://www.hardwired.dev</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>SSH připojení pomocí ESP32</title>
		<link>https://www.hardwired.dev/2024/09/25/ssh-pripojeni-pomoci-esp32/</link>
		
		<dc:creator><![CDATA[John Doe]]></dc:creator>
		<pubDate>Wed, 25 Sep 2024 12:09:47 +0000</pubDate>
				<category><![CDATA[Arduino]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[IOT]]></category>
		<category><![CDATA[automation]]></category>
		<category><![CDATA[esp32]]></category>
		<category><![CDATA[espressif]]></category>
		<category><![CDATA[home-automation]]></category>
		<category><![CDATA[iot]]></category>
		<category><![CDATA[libssh-esp32]]></category>
		<category><![CDATA[platformio]]></category>
		<category><![CDATA[ssh]]></category>
		<category><![CDATA[wifi]]></category>
		<guid isPermaLink="false">https://www.hardwired.dev/?p=2356</guid>

					<description><![CDATA[<p>V dnešním článku se podíváme na to, jak se z ESP32 development boardu připojit pomocí SSH ke vzdálenému počítači. Pro &#62;&#62;&#62;</p>
<p>The post <a href="https://www.hardwired.dev/2024/09/25/ssh-pripojeni-pomoci-esp32/">SSH připojení pomocí ESP32</a> first appeared on <a href="https://www.hardwired.dev">Hard Wired</a>.</p>]]></description>
										<content:encoded><![CDATA[<div id="bsf_rt_marker"></div><p>V dnešním článku se podíváme na to, jak se z <a href="https://vi.aliexpress.com/item/1005001621773806.html">ESP32 development boardu</a> připojit pomocí <a href="https://cs.wikipedia.org/wiki/Secure_Shell">SSH</a> ke vzdálenému počítači.</p>
<p>Pro vývoj je použito <a href="https://platformio.org/">PlatformIO</a>.</p>
<h1>platformio.ini</h1>
<pre><code class="language-ini">[env:esp32dev]
platform = espressif32
board = esp32dev
framework = arduino
monitor_speed = 115200
lib_deps = ewpa/LibSSH-ESP32@^4.2.0</code></pre>
<h1>main.cpp</h1>
<p>Jediná externí závislost je <code>libssh-esp32</code>. </p>
<pre><code class="language-cpp">#include &lt;Arduino.h&gt;
#include &lt;WiFi.h&gt;
#include &lt;libssh_esp32.h&gt;
#include &quot;libssh_esp32_config.h&quot;
#include &lt;libssh/libssh.h&gt;
#include &lt;vector&gt;
#include &lt;string&gt;</code></pre>
<p>Budeme potřebovat SSID WiFi sítě a heslo.</p>
<pre><code class="language-cpp">const char *ssid = &quot;ssid-vasi-wifi&quot;;
const char *password = &quot;vase-nejtajnejsi-heslo&quot;;</code></pre>
<p>Potřebujeme nastavit přihlašovací údaje pro SSH a příkaz který po přihlášení provedeme.</p>
<pre><code class="language-cpp">const int ssh_port = 22;
const char *ssh_username = &quot;pi&quot;;
const char *ssh_password = &quot;super-tajne-heslo&quot;;
const char *ssh_command = &quot;ls -l&quot;;</code></pre>
<p>Dále seznam IP adres serverů na které se chceme připojit.</p>
<pre><code class="language-cpp">std::vector&lt;std::string&gt; server_ips = {
    &quot;192.168.1.254&quot;,
};</code></pre>
<p>Vytvoříme funkci pro připojení k WiFi. Na konci vypíšeme do konzole MAC adresu přístupového bodu, ke kterému jsme se připojili.</p>
<pre><code class="language-cpp">void connectToWiFi()
{
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED)
    {
        delay(1000);
        Serial.println(&quot;Connecting to WiFi..&quot;);
    }
    Serial.print(&quot;Připojeno k AP s MAC: &quot;);
    Serial.println(WiFi.BSSIDstr());
}</code></pre>
<p>Ted ta nejdelší část. Funkce co vytvoří SSH spojení, provede příkaz a výsledek vypíše na standardní výstup. Funkce si po sobě uklízí.</p>
<pre><code class="language-cpp">/**
 * Execute SSH Command
 *
 * @param ip Server IP
 * @param username SSH Username
 * @param password SSH Password
 * @param command Command to execute
 */
void executeSSHCommand(const char *ip, const char *username, const char *password, const char *command)
{
    // Create a new SSH session
    ssh_session session = ssh_new();
    if (session == NULL)
    {
        Serial.println(&quot;Failed to create SSH session&quot;);
        return;
    }

    // Set SSH options for the session
    ssh_options_set(session, SSH_OPTIONS_HOST, ip);
    ssh_options_set(session, SSH_OPTIONS_USER, username);

    // Connect to SSH server
    int rc = ssh_connect(session);
    if (rc != SSH_OK)
    {
        Serial.println(&quot;Failed to connect to SSH server&quot;);
        return;
    }

    // Verify the server&#039;s identity
    rc = ssh_userauth_password(session, NULL, password);
    if (rc != SSH_AUTH_SUCCESS)
    {
        Serial.println(&quot;Failed to authenticate&quot;);
        return;
    }

    // Create a new SSH channel
    ssh_channel channel = ssh_channel_new(session);
    if (channel == NULL)
    {
        Serial.println(&quot;Failed to create SSH channel&quot;);
        return;
    }

    // Open a new SSH session
    rc = ssh_channel_open_session(channel);
    if (rc != SSH_OK)
    {
        Serial.println(&quot;Failed to open SSH session&quot;);
        return;
    }

    // Execute the command
    rc = ssh_channel_request_exec(channel, command);
    if (rc != SSH_OK)
    {
        Serial.println(&quot;Failed to execute command&quot;);
        return;
    }

    // Read the output of the command
    char buffer[256];
    int nbytes; // Number of bytes read
    nbytes = ssh_channel_read(channel, buffer, sizeof(buffer), 0);
    while (nbytes &gt; 0)
    {
        if (write(1, buffer, nbytes) != nbytes) // Write to stdout
        {
            Serial.println(&quot;Failed to write to stdout&quot;);
            return;
        }
        nbytes = ssh_channel_read(channel, buffer, sizeof(buffer), 0);
    }

    // Check if there was an error reading from the channel
    if (nbytes &lt; 0)
    {
        Serial.println(&quot;Failed to read from SSH channel&quot;);
        return;
    }

    // Send EOF and close the channel
    ssh_channel_send_eof(channel);

    // Close the channel
    ssh_channel_close(channel);

    // Free the channel
    ssh_channel_free(channel);

    // Disconnect the session
    ssh_disconnect(session);

    // Free the session
    ssh_free(session);
}</code></pre>
<p>Teď potřebujeme funkci která provede SSH příkaz pro všechny naše servery, které jsou definované v <code>server_ips</code>.</p>
<pre><code class="language-cpp">/**
 * Execute SSH Command on all servers
 * 
 * @param username SSH Username
 * @param password SSH Password
 * @param command Command to execute
 */
void executeSSHCommandOnAllServers(const char *username, const char *password, const char *command)
{
    for (std::string ip : server_ips)
    {
        executeSSHCommand(ip.c_str(), username, password, command);
    }
}</code></pre>
<p>Teď už jen zbývá provést vše při startu ESPčka.</p>
<pre><code class="language-cpp">void setup()
{
    Serial.begin(115200);
    while (!Serial)
    {
        ; // Wait for serial to be ready
    }

    connectToWiFi();
    ssh_init();
    executeSSHCommandOnAllServers(ssh_username, ssh_password, ssh_command);
}</code></pre>
<p>Hlavní smyčku programu pro tento příklad necháme odpočívat.</p>
<pre><code class="language-cpp">void loop()
{
    delay(1000); // Delay for 1 second
}</code></pre>
<p>To je vše. Po kompilaci, nahrání kódu a spuštění ESPčka se připojí k WiFi a poté provede SSH připojení na zadané IP adresy a provede <code>ls -l</code> příkaz. Ten vypíše do konzole.</p>
<h1>main.cpp full</h1>
<pre><code class="language-cpp">#include &lt;Arduino.h&gt;
#include &lt;WiFi.h&gt;
#include &lt;libssh_esp32.h&gt;
#include &quot;libssh_esp32_config.h&quot;
#include &lt;libssh/libssh.h&gt;
#include &lt;vector&gt;
#include &lt;string&gt;

// WiFi Credentials
const char *ssid = &quot;ssid-vasi-wifi&quot;;
const char *password = &quot;vase-nejtajnejsi-heslo&quot;;

// SSH Credentials
const int ssh_port = 22;
const char *ssh_username = &quot;pi&quot;;
const char *ssh_password = &quot;super-tajne-helso&quot;;
const char *ssh_command = &quot;ls -l&quot;;

// Server IPs List
std::vector&lt;std::string&gt; server_ips = {
    &quot;192.168.1.254&quot;,
};

/**
 * Connect to WiFi
 */
void connectToWiFi()
{
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED)
    {
        delay(1000);
        Serial.println(&quot;Connecting to WiFi..&quot;);
    }
    Serial.print(&quot;Připojeno k AP s MAC: &quot;);
    Serial.println(WiFi.BSSIDstr());
}

/**
 * Execute SSH Command
 *
 * @param ip Server IP
 * @param username SSH Username
 * @param password SSH Password
 * @param command Command to execute
 */
void executeSSHCommand(const char *ip, const char *username, const char *password, const char *command)
{
    // Create a new SSH session
    ssh_session session = ssh_new();
    if (session == NULL)
    {
        Serial.println(&quot;Failed to create SSH session&quot;);
        return;
    }

    // Set SSH options for the session
    ssh_options_set(session, SSH_OPTIONS_HOST, ip);
    ssh_options_set(session, SSH_OPTIONS_USER, username);

    // Connect to SSH server
    int rc = ssh_connect(session);
    if (rc != SSH_OK)
    {
        Serial.println(&quot;Failed to connect to SSH server&quot;);
        return;
    }

    // Verify the server&#039;s identity
    rc = ssh_userauth_password(session, NULL, password);
    if (rc != SSH_AUTH_SUCCESS)
    {
        Serial.println(&quot;Failed to authenticate&quot;);
        return;
    }

    // Create a new SSH channel
    ssh_channel channel = ssh_channel_new(session);
    if (channel == NULL)
    {
        Serial.println(&quot;Failed to create SSH channel&quot;);
        return;
    }

    // Open a new SSH session
    rc = ssh_channel_open_session(channel);
    if (rc != SSH_OK)
    {
        Serial.println(&quot;Failed to open SSH session&quot;);
        return;
    }

    // Execute the command
    rc = ssh_channel_request_exec(channel, command);
    if (rc != SSH_OK)
    {
        Serial.println(&quot;Failed to execute command&quot;);
        return;
    }

    // Read the output of the command
    char buffer[256];
    int nbytes; // Number of bytes read
    nbytes = ssh_channel_read(channel, buffer, sizeof(buffer), 0);
    while (nbytes &gt; 0)
    {
        if (write(1, buffer, nbytes) != nbytes) // Write to stdout
        {
            Serial.println(&quot;Failed to write to stdout&quot;);
            return;
        }
        nbytes = ssh_channel_read(channel, buffer, sizeof(buffer), 0);
    }

    // Check if there was an error reading from the channel
    if (nbytes &lt; 0)
    {
        Serial.println(&quot;Failed to read from SSH channel&quot;);
        return;
    }

    // Send EOF and close the channel
    ssh_channel_send_eof(channel);

    // Close the channel
    ssh_channel_close(channel);

    // Free the channel
    ssh_channel_free(channel);

    // Disconnect the session
    ssh_disconnect(session);

    // Free the session
    ssh_free(session);
}

/**
 * Execute SSH Command on all servers
 *
 * @param username SSH Username
 * @param password SSH Password
 * @param command Command to execute
 */
void executeSSHCommandOnAllServers(const char *username, const char *password, const char *command)
{
    for (std::string ip : server_ips)
    {
        executeSSHCommand(ip.c_str(), username, password, command);
    }
}

void setup()
{
    Serial.begin(115200);
    while (!Serial)
    {
        ; // Wait for serial to be ready
    }

    connectToWiFi();
    ssh_init();
    executeSSHCommandOnAllServers(ssh_username, ssh_password, ssh_command);
}

void loop()
{
    delay(1000); // Delay for 1 second
}
</code></pre>

<div class="twitter-share"><a href="https://twitter.com/intent/tweet?url=https%3A%2F%2Fwww.hardwired.dev%2F2024%2F09%2F25%2Fssh-pripojeni-pomoci-esp32%2F&#038;via=hessevalentino" class="twitter-share-button">Tweet</a></div><p>The post <a href="https://www.hardwired.dev/2024/09/25/ssh-pripojeni-pomoci-esp32/">SSH připojení pomocí ESP32</a> first appeared on <a href="https://www.hardwired.dev">Hard Wired</a>.</p>]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
