One place for hosting & domains

      Настройка Jupyter Notebook с помощью Python 3 в Ubuntu 20.04 и подключение через туннель SSH


      Введение

      Jupyter Notebook — веб-приложение с открытым исходным кодом, позволяющее создавать интерактивный код, визуализации и другие элементы и делиться ими. Этот инструмент можно использовать с несколькими языками программирования, включая Python, Julia, R, Haskell и Ruby. Он часто используется для работы с данными, статистическими моделями и машинным обучением.

      Блокноты Jupyter (или просто блокноты) — это документы, генерируемые приложением Jupyter Notebook, которые содержат компьютерный код и форматированные текстовые элементы (параграф, цитаты, изображения, ссылки и т.д.), которые помогают отображать и делиться воспроизводимые разработки. Они могут стать отличным инструментом для презентаций, основанных на данных или программном коде, а также хорошим средством для преподавания.

      В этом обучающем модуле мы расскажем о настройке запуска Jupyter Notebook на сервере Ubuntu 20.04 и продемонстрируем процедуры подключения и использования блокнотов с локального компьютера через туннели. К концу этого руководства вы сможете запускать код Python 3 с помощью Jupyter Notebook, запущенном на удаленном сервере.

      Предварительные требования

      Для прохождения этого обучающего модуля вам потребуется новый экземпляр сервера Ubuntu 20.04 с базовым брандмауэром и пользователем с привилегиями sudo и без привилегий root. Чтобы узнать, как настроить такой сервер, воспользуйтесь нашим руководством по начальной настройке сервера.

      Шаг 1 — Настройка Python

      Для начала процесса настройки мы установим зависимости, которые нам потребуется для нашей среды программирования Python, из репозиториев Ubuntu. В Ubuntu 20.04 предустанавлен Python 3. Немного позднее мы используем диспетчер пакетов Python pip для установки дополнительных компонентов.

      Сначала нам нужно обновить локальный индекс пакетов apt, а затем загрузить и установить пакеты:

      Затем установите pip и заголовочные файлы Python, которые используются определенными зависимостями Jupyter:

      • sudo apt install python3-pip python3-dev

      Теперь мы можем перейти к настройке виртуальной среды Python, куда мы будем устанавливать Jupyter.

      Шаг 2 — Создание виртуальной среды Python для Jupyter

      Теперь, когда у нас есть Python 3, а заголовочные файлы и pip готовы к запуску, мы можем создать виртуальную среду Python для управления нашими проектами. Мы установим Jupyter в эту виртуальную среду.

      Для этого нам потребуется доступ к virtualenv, который мы можем установить с помощью pip.

      Обновите pip и установите пакет с помощью следующей команды:

      • sudo -H pip3 install --upgrade pip
      • sudo -H pip3 install virtualenv

      Флаг -H гарантирует, что политика безопасности устанавливает переменную среды home в домашнюю директорию пользователя.

      После установки virtualenv мы можем начать формирование нашей среды. Создайте каталог для файлов нашего проекта и перейдите в этот каталог. Мы назовем ее my_project_dir, но вы должны использовать имя, которое понятно вам и согласуется с тем, над чем вы работаете.

      • mkdir ~/my_project_dir
      • cd ~/my_project_dir

      В директории проекта мы создадим виртуальную среду Python. Для целей данного руководства мы назовем ее my_project_env, но вы должны использовать название, соответствующее вашему проекту.

      • virtualenv my_project_env

      Эта команда создаст каталог my_project_env в каталоге my_project_dir. В этот каталог будут установлены локальная версия Python и локальная версия pip. Мы можем использовать ее для установки и настройки изолированной среды Python для Jupyter.

      Перед созданием Jupyter нам потребуется активировать виртуальную среду. Для этого можно использовать следующую команду:

      • source my_project_env/bin/activate

      Командная строка изменится, показывая, что теперь вы работаете в виртуальной среде Python. Командная строка теперь будет выглядеть примерно так: (my_project_env)user@host:~/my_project_dir$.

      Вы готовы к выполнению установки Jupyter в виртуальную среду.

      Шаг 3 — Установка Jupyter

      При запущенной виртуальной среде установите Jupyter с помощью локального экземпляра pip.

      Примечание: если виртуальная среда активна (когда перед командной строкой стоит (my_project_env)), необходимо использовать pip вместо pip3, даже если вы используете Python 3. Копия инструмента в виртуальной среде всегда имеет имя pip вне зависимости от версии Python.

      В данный момент вы успешно установили все программное обеспечение, необходимое для запуска Jupyter. Теперь мы можем запустить сервер Notebook.

      Шаг 4 — Запуск Jupyter Notebook

      Теперь у вас есть все, что нужно для запуска Jupyter Notebook! Для его запуска воспользуйтесь следующей командой:

      Журнал активности Jupyter Notebook будет выведен в командной строке. При запуске Jupyter Notebook будет использоваться порт с конкретным номером. Первый Notebook, который вы будете запускать, обычно использует порт 8888. Чтобы проверить, какой номер порта использует Jupyter, см. вывод команды, которую вы использовали для запуска:

      Output

      [I 21:23:21.198 NotebookApp] Writing notebook server cookie secret to /run/user/1001/jupyter/notebook_cookie_secret [I 21:23:21.361 NotebookApp] Serving notebooks from local directory: /home/sammy/my_project_dir [I 21:23:21.361 NotebookApp] The Jupyter Notebook is running at: [I 21:23:21.361 NotebookApp] http://localhost:8888/?token=1fefa6ab49a498a3f37c959404f7baf16b9a2eda3eaa6d72 [I 21:23:21.361 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation). [W 21:23:21.361 NotebookApp] No web browser found: could not locate runnable browser. [C 21:23:21.361 NotebookApp] Copy/paste this URL into your browser when you connect for the first time, to login with a token: http://localhost:8888/?token=1fefa6ab49a498a3f37c959404f7baf16b9a2eda3eaa6d72

      Если вы запускаете Jupyter Notebook на локальном компьютере (а не на сервере), вы можете перейти к отображаемому URL-адресу для подключения к Jupyter Notebook. Если вы запускаете Jupyter Notebook на сервере, вам нужно будет подключаться к серверу с помощью туннеля SSH, как указано в следующем разделе.

      В данный момент вы можете сохранить соединение SSH открытым и поддерживать Jupyter Notebook в рабочем состоянии, или закрыть приложение и снова запустить его после настройки туннеля SSH. Давайте завершим процесс Jupyter Notebook. Мы запустим его снова после настройки туннеля SSH. Чтобы остановить процесс Jupyter Notebook, нажмите CTRL+C, введите Y, а затем ENTER для подтверждения. В результате будет отображен следующий вывод:

      Output

      [C 21:28:28.512 NotebookApp] Shutdown confirmed [I 21:28:28.512 NotebookApp] Shutting down 0 kernels

      Теперь мы настроим туннель SSH, чтобы получить доступ к Notebook.

      Шаг 5 — Подключение к серверу с помощью туннеля SSH

      В этом разделе мы покажем, как подключиться к веб-интерфейсу Jupyter Notebook с помощью туннеля SSH. Поскольку Jupyter Notebook будет работать на конкретном порту на сервере (например, :8888, :8889 и т. д.), туннель SSH позволяет безопасно подключаться к порту сервера.

      В следующих двух подразделах описано, как создать туннель SSH в (1) Mac, Linux или (2) Windows. См. подраздел для вашего локального компьютера.

      Туннель SSH в Mac или Linux

      Если вы используете локальный компьютер под управлением Mac или Linux, процедура создания туннеля SSH будет аналогична процедуре использования SSH для входа на удаленный сервер. Единственное отличие будет заключаться в наличии дополнительных параметров команды ssh. В этом подразделе будут показаны дополнительные параметры, необходимые команде ssh для успешного создания туннеля.

      Создание туннелей SSH может быть осуществлено с помощью следующей команды SSH, которую необходимо ввести в новом окне локальной командной строки:

      • ssh -L 8888:localhost:8888 your_server_username@your_server_ip

      Команда ssh открывает соединение SSH, но -L указывает, что данный порт на локальном хосте (клиент) будет отправляться на заданный хост и порт на удаленном конце (сервер). Это значит, что бы ни было запущено на втором порту (например, 8888) на сервере, оно появится на первом порту (например, 8888) на локальном компьютере.

      Вы можете изменить порт 8888 на один из ваших портов, чтобы избежать использования порта, который уже используется другим процессом.

      server_username — это ваше имя пользователя (например, sammy) на сервере, который вы создали, а your_server_ip — это IP-адрес вашего сервера.

      Например, для имени пользователя sammy и адреса сервера 203.0.113.0, команда будет выглядеть следующим образом:

      • ssh -L 8888:localhost:8888 sammy@203.0.113.0

      Если после запуска команды ssh -L не появится ошибок, вы можете перейти в среду программирования и запустить Jupyter Notebook:

      Вы получите вывод с URL-адресом. В веб-браузере на локальном компьютере откройте веб-интерфейс Jupyter Notebook с URL-адресом, который начинается с http://localhost:8888. Убедитесь, что номер маркера включен, либо введите строку с номером маркера при запросе в http://localhost:8888.

      Создание туннелей SSH с использованием Windows и PuTTY

      Если вы используете Windows, вы можете создать туннель SSH с помощью Putty.

      Введите URL-адрес сервера или IP-адрес в качестве имени хоста, как показано ниже:

      Задайте имя хоста для туннеля SSH

      Далее нажмите SSH в нижней части левой панели, чтобы расширить меню, а затем нажмите Tunnels (Туннели). Введите локальный номер порта, который вы хотите использовать для доступа к Jupyter на локальном компьютере. Выберите 8000 или выше, чтобы избежать использования портов, которые уже используются другими службами, и задайте назначение localhost:8888, где :8888 — номер порта, на котором запущен Jupyter Notebook.

      Затем нажмите кнопку Add (Добавить), после чего порты должны появиться в списке Forwarded ports (Перенаправляемые порты):

      Список перенаправляемых портов

      После этого нажмите кнопку Open (Открыть) для подключения к серверу через SSH и туннель с нужными портами. Перейдите на http://localhost:8000 (или любой порт на выбор) в веб-браузере для подключения к Jupyter Notebook, запущенному на сервере. Убедитесь, что номер маркера включен, либо введите строку с номером маркера при запросе в http://localhost:8000.

      Шаг 6 — Использование Jupyter Notebook

      В этом разделе описываются основы использования Jupyter Notebook. Если у вас нет запущенного Jupyter Notebook, запустите его с помощью команды jupyter notebook.

      Теперь вы должны быть подключены к нему с помощью браузера. Jupyter Notebook — это очень мощный инструмент с множеством функций. В этом разделе будет описан ряд базовых функций, необходимых для начала использования Notebook. Jupyter Notebook будет отображать все файлы и папки в директории, в которой он запущен, поэтому, если вы работаете над проектом, убедитесь, что вы можете запустить его из директории проекта.

      Чтобы создать новый файл Notebook, выберите New (Новый) > Python 3 в выпадающем меню в верхнем правом углу:

      Создание нового блокнота Python 3

      В результате откроется Notebook. Теперь мы можем запустить код Python в ячейке или изменить ячейку на разметку. Например, измените первую ячейку, чтобы она могла принимать разметку, нажмите Cell (Ячейка) > Cell Type (Тип ячейки) > Markdown (Разметка) в верхней панели навигации. Теперь мы можем добавлять записи с помощью разметки и даже включать уравнения, созданные в LaTeX, поместив их между символами $$. Например, введите в ячейку следующее после ее переключения на разметку:

      # First Equation
      
      Let us now implement the following equation:
      $$ y = x^2$$
      
      where $x = 2$
      

      Чтобы превратить разметку в отформатированный текст, нажмите клавиши CTRL и ENTER. Вы получите примерно следующий результат:

      результат разметки

      Вы можете использовать ячейки разметки для заметок и документирования программного кода. Теперь реализуем это уравнение и распечатаем результат. Нажмите на верхнюю ячейку и нажмите клавиши ALT и ENTER одновременно для добавления ячейки под ней. Введите в добавленную ячейку следующий код.

      x = 2
      y = x**2
      print(y)
      

      Для запуска кода нажмите CTRL+ENTER. Вы получите следующие результаты:

      результаты первого уравнения

      Теперь вы можете импортировать модули и использовать Notebook, как и любую другую среду разработки Python!

      Заключение

      Поздравляем! Теперь вы можете писать воспроизводимый код Python и записи в Markdown с помощью Jupyter Notebook. Для быстрого ознакомления с интерфейсом Jupyter Notebook выберите Help (Справка) > User Interface Tour (Знакомство с пользовательским интерфейсом) в верхнем меню навигации.

      Здесь вы можете запустить проект анализа данных и визуализации, ознакомившись со статьей Анализ данных и визуализация с pandas и Jupyter Notebook в Python 3.



      Source link

      Cómo configurar claves de SSH en Ubuntu 20.04


      Introducción

      SSH, o shell seguro, es un protocolo cifrado que se usa para administrar servidores y comunicarse con ellos. Al trabajar con un servidor de Ubuntu, es probable que pase la mayor parte de su tiempo en una sesión de terminal conectada a su servidor a través de SSH.

      En esta guía, nos centraremos en configurar claves SSH para una instalación de Ubuntu 20.04. Las claves de SSH proporcionan una alternativa sencilla y segura para iniciar sesión en su servidor y se recomiendan para todos los usuarios.

      Paso 1: Crear el par de claves

      El primer paso es crear un par de claves en la máquina cliente (por lo general, su computadora):

      Por defecto, las versiones de ssh-keygen crearán un par de claves RSA de 3072 bit, que es lo suficientemente seguro para la mayoría de casos de uso (opcionalmente puede pasar el indicador -b 4096 para crear una clave de 4096 bit más grande).

      Después de ingresar el comando, verá el siguiente resultado:

      Output

      Generating public/private rsa key pair. Enter file in which to save the key (/your_home/.ssh/id_rsa):

      Presione ENTER para guardar el par de claves en el subdirectorio .ssh/ de su directorio principal, o especificar una ruta alternativa.

      Si generó previamente un par de claves de SSH, puede ver el siguiente mensaje:

      Output

      /home/your_home/.ssh/id_rsa already exists. Overwrite (y/n)?

      Si elige sobrescribir la clave en el disco, ya no podrá autenticar usando la clave anterior. Tenga mucho cuidado al convalidar la operación, ya que este es un proceso destructivo que no puede revertirse.

      Debería ver el siguiente mensaje:

      Output

      Enter passphrase (empty for no passphrase):

      Aquí, puede introducir una frase de contraseña segura, lo cual se recomienda mucho. Una frase de contraseña agrega una capa de seguridad adicional para evitar el inicio de sesión de usuarios no autorizados. Para obtener más información sobre seguridad, consulte nuestro tutorial Cómo configurar la autenticación basada en claves de SSH en un servidor de Linux.

      Verá un resultado similar al siguiente:

      Output

      Your identification has been saved in /your_home/.ssh/id_rsa Your public key has been saved in /your_home/.ssh/id_rsa.pub The key fingerprint is: SHA256:/hk7MJ5n5aiqdfTVUZr+2Qt+qCiS7BIm5Iv0dxrc3ks user@host The key's randomart image is: +---[RSA 3072]----+ | .| | + | | + | | . o . | |o S . o | | + o. .oo. .. .o| |o = oooooEo+ ...o| |.. o *o+=.*+o....| | =+=ooB=o.... | +----[SHA256]-----+

      Ahora dispondrá de una clave pública y privada que puede usar para realizar la autenticación. El siguiente paso es ubicar la clave pública en su servidor a fin de poder usar la autenticación basada en claves de SSH para iniciar sesión.

      Paso 2: Copiar la clave pública al servidor Ubuntu

      La alternativa más rápida para copiar su clave pública al host de Ubuntu es usar una utilidad llamada ssh-copy-id. Debido a su simplicidad, este método se recomienda mucho si está disponible. Si no tiene la utilidad ssh-copy-id disponible en su máquina cliente, puede usar uno de los dos métodos alternativos proporcionados en esta sección (copiar mediante SSH con contraseña o copiar manualmente la clave).

      Copiar clave pública usando ssh-copy-id

      La herramienta ssh-copy-id se incluye por defecto en muchos sistemas operativos. Por ello, es posible que tenga la posibilidad de disponer de ella en su sistema local. Para que este método funcione, ya debe disponer de acceso con SSH basado en contraseña en su servidor.

      Para usar la utilidad, especifique el host remoto al que desee conectarse y la cuenta de usuario a la que tenga acceso mediante SSH con contraseña. Esta es la cuenta a la que se copiará su clave de SSH pública.

      La sintaxis es la siguiente:

      • ssh-copy-id username@remote_host

      Es posible que vea el siguiente mensaje:

      Output

      The authenticity of host '203.0.113.1 (203.0.113.1)' can't be established. ECDSA key fingerprint is fd:fd:d4:f9:77:fe:73:84:e1:55:00:ad:d6:6d:22:fe. Are you sure you want to continue connecting (yes/no)? yes

      Esto significa que su computadora local no reconoce el host remoto. Esto sucederá la primera vez que establezca conexión con un nuevo host. Escriba “yes” y presione ENTER para continuar.

      A continuación, la utilidad analizará su cuenta local en busca de la clave id_rsa.pub que creamos antes. Cuando la encuentre, le solicitará la contraseña de la cuenta del usuario remoto:

      Output

      /usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed /usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys username@203.0.113.1's password:

      Escriba la contraseña (por motivos de seguridad, no se mostrará lo que escriba) y pulse ENTER. La utilidad se conectará a la cuenta en el host remoto usando la contraseña que proporcionó. Luego, copie el contenido de su clave ~/.ssh/id_rsa.pub a un archivo en el directorio principal de la cuenta remota ~/.ssh, llamado authorized_keys.

      Debería ver el siguiente resultado:

      Output

      Number of key(s) added: 1 Now try logging into the machine, with: "ssh 'username@203.0.113.1'" and check to make sure that only the key(s) you wanted were added.

      En este punto, su clave id_rsa.pub se habrá cargado en la cuenta remota. |Puede continuar con el paso 3.

      Copiar clave pública usando SSH

      Si no tiene ssh-copy-id disponible, pero tiene acceso de SSH basado en contraseña a una cuenta de su servidor, puede cargar sus claves usando un método de SSH convencional.

      Podemos hacer esto usando el comando cat para leer el contenido de la clave de SSH pública en nuestra computadora local y canalizando esto a través de una conexión SSH al servidor remoto.

      Por otra parte, podemos asegurarnos de que el directorio ~/.ssh exista y tenga los permisos correctos conforme a la cuenta que usamos.

      Luego podemos transformar el contenido que canalizamos a un archivo llamado authorized_keys dentro de este directorio. Usaremos el símbolo de redireccionamiento >> para anexar el contenido en lugar de sobrescribirlo. Esto nos permitirá agregar claves sin eliminar claves previamente agregadas.

      El comando completo tiene este aspecto:

      • cat ~/.ssh/id_rsa.pub | ssh username@remote_host "mkdir -p ~/.ssh && touch ~/.ssh/authorized_keys && chmod -R go= ~/.ssh && cat >> ~/.ssh/authorized_keys"

      Es posible que vea el siguiente mensaje:

      Output

      The authenticity of host '203.0.113.1 (203.0.113.1)' can't be established. ECDSA key fingerprint is fd:fd:d4:f9:77:fe:73:84:e1:55:00:ad:d6:6d:22:fe. Are you sure you want to continue connecting (yes/no)? yes

      Esto significa que su computadora local no reconoce el host remoto. Esta pasará la primera vez que establezca conexión con un nuevo host. Escriba yes y presione ENTER para continuar.

      Posteriormente, deberá recibir la solicitud de introducir la contraseña de la cuenta de usuario remota:

      Output

      username@203.0.113.1's password:

      Una vez que ingrese su contraseña, el contenido de su clave id_rsa.pub se copiará al final del archivo authorized_keys de la cuenta del usuario remoto. Continúe con el paso 3 si el procedimiento se completó de forma correcta.

      Copiar la clave pública de forma manual

      Si no tiene disponibilidad de acceso de SSH basado en contraseña a su servidor, deberá completar el proceso anterior de forma manual.

      Habilitaremos el contenido de su archivo id_rsa.pub para el archivo ~/.ssh/authorized_keys en su máquina remota.

      Para mostrar el contenido de su clave id_rsa.pub, escriba esto en su computadora local:

      Verá el contenido de la clave, que debería tener un aspecto similar a este:

      Output

      ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQCqql6MzstZYh1TmWWv11q5O3pISj2ZFl9HgH1JLknLLx44+tXfJ7mIrKNxOOwxIxvcBF8PXSYvobFYEZjGIVCEAjrUzLiIxbyCoxVyle7Q+bqgZ8SeeM8wzytsY+dVGcBxF6N4JS+zVk5eMcV385gG3Y6ON3EG112n6d+SMXY0OEBIcO6x+PnUSGHrSgpBgX7Ks1r7xqFa7heJLLt2wWwkARptX7udSq05paBhcpB0pHtA1Rfz3K2B+ZVIpSDfki9UVKzT8JUmwW6NNzSgxUfQHGwnW7kj4jp4AT0VZk3ADw497M2G/12N0PPB5CnhHf7ovgy6nL1ikrygTKRFmNZISvAcywB9GVqNAVE+ZHDSCuURNsAInVzgYo9xgJDW8wUw2o8U77+xiFxgI5QSZX3Iq7YLMgeksaO4rBJEa54k8m5wEiEE1nUhLuJ0X/vh2xPff6SQ1BL/zkOhvJCACK6Vb15mDOeCSq54Cr7kvS46itMosi/uS66+PujOO+xt/2FWYepz6ZlN70bRly57Q06J+ZJoc9FfBCbCyYH7U/ASsmY095ywPsBo1XQ9PqhnN1/YOorJ068foQDNVpm146mUpILVxmq41Cj55YKHEazXGsdBIbXWhcrRf4G2fJLRcGUr9q8/lERo9oxRm5JFX6TCmj6kmiFqv+Ow9gI0x8GvaQ== demo@test

      Acceda a su host remoto usando el método que esté a su disposición.

      Una vez que tenga acceso a su cuenta en el servidor remoto, debe asegurarse de que exista el directorio ~/.ssh. Con este comando se creará el directorio, si es necesario. Si este último ya existe, no se creará:

      Ahora, podrá crear o modificar el archivo authorized_keys dentro de este directorio. Puede agregar el contenido de su archivo id_rsa.pub al final del archivo authorized_keys y, si es necesario, crear este último con el siguiente comando:

      • echo public_key_string >> ~/.ssh/authorized_keys

      En el comando anterior, reemplace public_key_string por el resultado del comando cat ~/.ssh/id_rsa.pub que ejecutó en su sistema local. Debería iniciar con ssh-rsa AAAA....

      Por último, verificaremos que el directorio ~/.ssh y el archivo authorized_keys tengan el conjunto de permisos apropiados:

      Con esto, se eliminan de forma recursiva todos los permisos “grupo” y “otros” del directorio ~/.ssh/.

      Si está usando la cuenta root para configurar claves para una cuenta de usuario, también es importante que el directorio ~/.ssh pertenezca al usuario y no sea root:

      • chown -R sammy:sammy ~/.ssh

      En este tutorial, nuestro usuario recibe el nombre sammy, pero debe sustituir el nombre de usuario que corresponda en el comando anterior.

      Ahora podemos intentar la autenticación sin contraseña con nuestro servidor de Ubuntu.

      Paso 3: Autenticación en el servidor de Ubuntu con claves de SSH

      Si completó con éxito uno de los procedimientos anteriores, debería poder iniciar sesión en el host remoto sin la contraseña de la cuenta remota.

      El proceso básico es el mismo:

      Si es la primera vez que establece conexión con este host (si empleó el último método anterior), es posible que vea algo como esto:

      Output

      The authenticity of host '203.0.113.1 (203.0.113.1)' can't be established. ECDSA key fingerprint is fd:fd:d4:f9:77:fe:73:84:e1:55:00:ad:d6:6d:22:fe. Are you sure you want to continue connecting (yes/no)? yes

      Esto significa que su computadora local no reconoce el host remoto. Escriba “yes” y presione ENTER para continuar.

      Si no proporcionó una frase de contraseña para su clave privada, se iniciará sesión de inmediato. Si proporcionó una frase de contraseña para la clave privada al crearla, se solicitará que la introduzca ahora (tenga en cuenta que, por motivos de seguridad, las pulsaciones de teclas no se mostrarán en la sesión de terminal). Después de la autenticación, se debería abrir una nueva sesión de shell con la cuenta configurada en el servidor de Ubuntu.

      Si la autenticación basada en claves se realizó con éxito, puede aprender a proteger más su sistema inhabilitando la autenticación con contraseña.

      Paso 4: Inhabilitar la autenticación con contraseña en su servidor

      Si pudo iniciar sesión en su cuenta usando SSH sin una contraseña, habrá configurado con éxito la autenticación basada en claves de SSH para su cuenta. Sin embargo, su mecanismo de autenticación basado en contraseña sigue activo. Esto significa que su servidor sigue expuesto a ataques de fuerza bruta.

      Antes de completar los pasos de esta sección, asegúrese de tener configurada la autenticación basada en claves de SSH para la cuenta root en este servidor o, preferentemente, la autenticación basada en clave de SSH para una cuenta no root en este servidor con privilegios sudo. Con este paso, se bloquearán los registros basados en contraseñas. Por lo tanto, es fundamental que se asegure de seguir teniendo acceso administrativo.

      Una vez que haya confirmado que su cuenta remota tiene privilegios administrativos, inicie sesión en su servidor remoto con claves de SSH, ya sea como root o con una cuenta con privilegios sudo. Luego, abra el archivo de configuración del demonio de SSH:

      • sudo nano /etc/ssh/sshd_config

      Dentro del archivo, busque una directiva llamada PasswordAuthentication. Esta línea puede ser eliminada con una # al principio de la línea. Elimine la línea quitando #, y establezca el valor a no. Esto deshabilitará su capacidad de iniciar sesión vía SSH usando las contraseñas de la cuenta:

      /etc/ssh/sshd_config

      . . .
      PasswordAuthentication no
      . . .
      

      Guarde y cierre el archivo cuando haya terminado pulsando CTRL + X, luego Y para confirmar que desea guardar el archivo y, por último, ENTER para cerrar nano. Para activar realmente estos cambios, debemos reiniciar el servicio sshd:

      • sudo systemctl restart ssh

      Como medida de precaución, abra una nueva ventana de terminal y compruebe que el servicio de SSH funcione correctamente antes de cerrar su sesión actual:

      Una vez que haya verificado que su servicio de SSH está funcionando correctamente, podrá cerrar de forma segura todas las sesiones de los servidores actuales.

      El demonio SSH de su servidor de Ubuntu ahora solo responderá a claves de SSH. Los inicios de sesión con contraseña han sido deshabilitados.

      Conclusión

      De esta manera, la autenticación basada en claves de SSH debería quedar configurada en su servidor. Esto le permitirá iniciar sesión sin proporcionar una contraseña de cuenta.

      Si desea obtener más información sobre cómo trabajar con SSH, consulte nuestra Guía de aspectos básicos de SSH.



      Source link

      How To Set Up Jupyter Notebook with Python 3 on Ubuntu 20.04 and Connect via SSH Tunneling


      Introduction

      Jupyter Notebook is an open-source web application that lets you create and share interactive code, visualizations, and more. This tool can be used with several programming languages, including Python, Julia, R, Haskell, and Ruby. It is often used for working with data, statistical modeling, and machine learning.

      Jupyter Notebooks (or just “Notebooks”) are documents produced by the Jupyter Notebook app which contain both computer code and rich text elements (paragraph, equations, figures, links, etc.) which aid in presenting and sharing reproducible research. They can therefore be an excellent tool to use for data-driven or programming-based presentations, or as a teaching tool.

      This tutorial will walk you through setting up Jupyter Notebook to run from an Ubuntu 20.04 server, as well as demonstrate how to connect to and use the notebook from a local machine via tunnelling. By the end of this guide, you will be able to run Python 3 code using Jupyter Notebook running on a remote server.

      Prerequisites

      In order to complete this guide, you should have a fresh Ubuntu 20.04 server instance with a basic firewall and a non-root user with sudo privileges configured. You can learn how to set this up by running through our initial server setup tutorial.

      Step 1 — Set Up Python

      To begin the process, we’ll install the dependencies we need for our Python programming environment from the Ubuntu repositories. Ubuntu 20.04 comes preinstalled with Python 3. We will use the Python package manager pip to install additional components a bit later.

      We first need to update the local apt package index and then download and install the packages:

      Next, install pip and the Python header files, which are used by some of Jupyter’s dependencies:

      • sudo apt install python3-pip python3-dev

      We can now move on to setting up a Python virtual environment into which we’ll install Jupyter.

      Step 2 — Create a Python Virtual Environment for Jupyter

      Now that we have Python 3, its header files, and pip ready to go, we can create a Python virtual environment to manage our projects. We will install Jupyter into this virtual environment.

      To do this, we first need access to the virtualenv command which we can install with pip.

      Upgrade pip and install the package by typing:

      • sudo -H pip3 install --upgrade pip
      • sudo -H pip3 install virtualenv

      The -H flag ensures that the security policy sets the home environment variable to the home directory of the target user.

      With virtualenv installed, we can start forming our environment. Create and move into a directory where we can keep our project files. We’ll call this my_project_dir, but you should use a name that is meaningful for you and what you’re working on.

      • mkdir ~/my_project_dir
      • cd ~/my_project_dir

      Within the project directory, we’ll create a Python virtual environment. For the purpose of this tutorial, we’ll call it my_project_env but you should call it something that is relevant to your project.

      • virtualenv my_project_env

      This will create a directory called my_project_env within your my_project_dir directory. Inside, it will install a local version of Python and a local version of pip. We can use this to install and configure an isolated Python environment for Jupyter.

      Before we install Jupyter, we need to activate the virtual environment. You can do that by typing:

      • source my_project_env/bin/activate

      Your prompt should change to indicate that you are now operating within a Python virtual environment. Your command prompt will now read something like this: (my_project_env)user@host:~/my_project_dir$.

      At this point, you’re ready to install Jupyter into this virtual environment.

      Step 3 — Install Jupyter

      With your virtual environment active, install Jupyter with the local instance of pip.

      Note: When the virtual environment is activated (when your prompt has (my_project_env) preceding it), use pip instead of pip3, even if you are using Python 3. The virtual environment’s copy of the tool is always named pip, regardless of the Python version.

      At this point, you’ve successfully installed all the software needed to run Jupyter. We can now start the Notebook server.

      Step 4 — Run Jupyter Notebook

      You now have everything you need to run Jupyter Notebook! To run it, execute the following command:

      A log of the activities of the Jupyter Notebook will be printed to the terminal. When you run Jupyter Notebook, it runs on a specific port number. The first Notebook you run will usually use port 8888. To check the specific port number Jupyter Notebook is running on, refer to the output of the command used to start it:

      Output

      [I 21:23:21.198 NotebookApp] Writing notebook server cookie secret to /run/user/1001/jupyter/notebook_cookie_secret [I 21:23:21.361 NotebookApp] Serving notebooks from local directory: /home/sammy/my_project_dir [I 21:23:21.361 NotebookApp] The Jupyter Notebook is running at: [I 21:23:21.361 NotebookApp] http://localhost:8888/?token=1fefa6ab49a498a3f37c959404f7baf16b9a2eda3eaa6d72 [I 21:23:21.361 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation). [W 21:23:21.361 NotebookApp] No web browser found: could not locate runnable browser. [C 21:23:21.361 NotebookApp] Copy/paste this URL into your browser when you connect for the first time, to login with a token: http://localhost:8888/?token=1fefa6ab49a498a3f37c959404f7baf16b9a2eda3eaa6d72

      If you are running Jupyter Notebook on a local computer (not on a server), you can navigate to the displayed URL to connect to Jupyter Notebook. If you are running Jupyter Notebook on a server, you will need to connect to the server using SSH tunneling as outlined in the next section.

      At this point, you can keep the SSH connection open and keep Jupyter Notebook running or you can exit the app and re-run it once you set up SSH tunneling. Let’s choose to stop the Jupyter Notebook process. We will run it again once we have SSH tunneling set up. To stop the Jupyter Notebook process, press CTRL+C, type Y, and then ENTER to confirm. The following output will be displayed:

      Output

      [C 21:28:28.512 NotebookApp] Shutdown confirmed [I 21:28:28.512 NotebookApp] Shutting down 0 kernels

      We’ll now set up an SSH tunnel so that we can access the Notebook.

      Step 5 — Connect to the Server Using SSH Tunneling

      In this section we will demonstrate how to connect to the Jupyter Notebook web interface using SSH tunneling. Since Jupyter Notebook will run on a specific port on the server (such as :8888, :8889 etc.), SSH tunneling enables you to connect to the server’s port securely.

      The next two subsections describe how to create an SSH tunnel from 1) a Mac or Linux, or 2) Windows. Please refer to the subsection for your local computer.

      SSH Tunneling with a Mac or Linux

      If you are using a Mac or Linux local computer, the steps for creating an SSH tunnel are similar to using SSH to log in to your remote server, except that there are additional parameters in the ssh command. This subsection will outline the additional parameters needed in the ssh command to tunnel successfully.

      SSH tunneling can be done by running the following SSH command in a new local terminal window:

      • ssh -L 8888:localhost:8888 your_server_username@your_server_ip

      The ssh command opens an SSH connection, but -L specifies that the given port on the local (client) host is to be forwarded to the given host and port on the remote side (server). This means that whatever is running on the second port number (e.g. 8888) on the server will appear on the first port number (e.g. 8888) on your local computer.

      Optionally change port 8888 to one of your choosing to avoid using a port already in use by another process.

      server_username is your username (e.g. sammy) on the server which you created and your_server_ip is the IP address of your server.

      For example, for the username sammy and the server address 203.0.113.0, the command would be:

      • ssh -L 8888:localhost:8888 sammy@203.0.113.0

      If no error shows up after running the ssh -L command, you can move into your programming environment and run Jupyter Notebook:

      You’ll receive output with a URL. From a web browser on your local machine, open the Jupyter Notebook web interface with the URL that starts with http://localhost:8888. Ensure that the token number is included, or enter the token number string when prompted at http://localhost:8888.

      SSH Tunneling with Windows and Putty

      If you are using Windows, you can create an SSH tunnel using Putty.

      First, enter the server URL or IP address as the hostname as shown:

      Set Hostname for SSH Tunnel

      Next, click SSH on the bottom of the left pane to expand the menu, and then click Tunnels. Enter the local port number you want to use to access Jupyter on your local machine. Choose 8000 or greater to avoid ports used by other services, and set the destination as localhost:8888 where :8888 is the number of the port that Jupyter Notebook is running on.

      Now click the Add button, and the ports should appear in the Forwarded ports list:

      Forwarded ports list

      Finally, click the Open button to connect to the server via SSH and tunnel the desired ports. Navigate to http://localhost:8000 (or whatever port you chose) in a web browser to connect to Jupyter Notebook running on the server. Ensure that the token number is included, or enter the token number string when prompted at http://localhost:8000.

      Step 6 — Using Jupyter Notebook

      This section goes over the fundamentals of using Jupyter Notebook. If you don’t currently have Jupyter Notebook running, start it with the jupyter notebook command.

      You should now be connected to it using a web browser. Jupyter Notebook is a very powerful tool with many features. This section will outline a few basic features to get you started using the Notebook. Jupyter Notebook will show all of the files and folders in the directory it is run from, so when you’re working on a project make sure to start it from the project directory.

      To create a new Notebook file, select New > Python 3 from the top right pull-down menu:

      Create a new Python 3 notebook

      This will open a Notebook. We can now run Python code in the cell or change the cell to markdown. For example, change the first cell to accept Markdown by clicking Cell > Cell Type > Markdown from the top navigation bar. We can now write notes using Markdown and even include equations written in LaTeX by putting them between the $$ symbols. For example, type the following into the cell after changing it to markdown:

      # First Equation
      
      Let us now implement the following equation:
      $$ y = x^2$$
      
      where $x = 2$
      

      To turn the markdown into rich text, press the CTRL and ENTER keys. You should receive output similar to the following:

      results of markdown

      You can use the markdown cells to make notes and document your code. Let’s implement that equation and print the result. Click on the top cell, then press the ALT and ENTER keys together to add a cell below it. Enter the following code in the new cell.

      x = 2
      y = x**2
      print(y)
      

      To run the code, press CTRL+ENTER. You’ll receive the following results:

      first equation results

      You now have the ability to import modules and use the Notebook as you would with any other Python development environment!

      Conclusion

      Congratulations! You should now be able to write reproducible Python code and notes in Markdown using Jupyter Notebook. To get a quick tour of Jupyter Notebook from within the interface, select Help > User Interface Tour from the top navigation menu to learn more.

      From here, you can begin a data analysis and visualization project by reading Data Analysis and Visualization with pandas and Jupyter Notebook in Python 3.



      Source link