如何在Ubuntu 20.04上使用Python 3设置Jupyter Notebook并通过SSH隧道连接

林绪
2023-12-01

介绍 (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 Notebook是一个开源Web应用程序,可让您创建和共享交互式代码,可视化文件等。 该工具可与多种编程语言一起使用,包括Python,Julia,R,Haskell和Ruby。 它通常用于处理数据,统计建模和机器学习。

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.

Jupyter Notebook(或“ Notebooks”)是Jupyter Notebook应用程序生成的文档,其中包含计算机代码和丰富的文本元素(段落,方程,图形,链接等),有助于呈现和共享可重复的研究。 因此,它们可以是用于数据驱动或基于编程的演示的出色工具,也可以作为教学工具。

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.

本教程将引导您设置Jupyter Notebook以从Ubuntu 20.04服务器运行,并演示如何通过隧道连接和从本地计算机使用笔记本。 在本指南结束时,您将能够使用在远程服务器上运行的Jupyter Notebook运行Python 3代码。

先决条件 (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.

为了完成本指南,您应该具有一个全新的Ubuntu 20.04服务器实例,该实例具有基本防火墙和配置了sudo特权的非root用户。 您可以通过运行我们的初始服务器设置教程来学习如何进行设置。

第1步-设置Python (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.

首先,我们将从Ubuntu存储库中安装Python编程环境所需的依赖项。 Ubuntu 20.04已预装Python3。稍后,我们将使用Python软件包管理器pip安装其他组件。

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

我们首先需要更新本地apt软件包索引,然后下载并安装软件包:

  • sudo apt update

    sudo apt更新

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

接下来,安装一些Jupyter依赖项使用的pip和Python头文件:

  • sudo apt install python3-pip python3-dev

    sudo apt安装python3-pip python3-dev

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

现在,我们可以继续设置要在其中安装Jupyter的Python虚拟环境。

第2步-为Jupyter创建Python虚拟环境 (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.

现在我们已经准备好使用Python 3,其头文件和pip,我们可以创建一个Python虚拟环境来管理我们的项目。 我们将Jupyter安装到此虚拟环境中。

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

为此,我们首先需要访问virtualenv命令,该命令可以通过pip安装。

Upgrade pip and install the package by typing:

通过输入以下内容来升级pip并安装软件包:

  • sudo -H pip3 install --upgrade pip

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

    须藤-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.

-H标志确保安全策略设置home环境变量设置为目标用户的主目录。

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.

安装virtualenv ,我们就可以开始形成环境了。 创建并移至一个目录,我们可以在其中保存项目文件。 我们将其称为my_project_dir ,但是您应该使用一个对您和您正在从事的工作有意义的名称。

  • mkdir ~/my_project_dir

    mkdir〜/ my_project_dir

  • cd ~/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.

在项目目录中,我们将创建一个Python虚拟环境。 就本教程而言,我们将其称为my_project_env但应将其命名为与您的项目相关的名称。

  • virtualenv my_project_env

    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.

这将创建一个名为my_project_env你的内my_project_dir目录。 在内部,它将安装Python的本地版本和pip的本地版本。 我们可以使用它为Jupyter安装和配置一个隔离的Python环境。

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

在安装Jupyter之前,我们需要激活虚拟环境。 您可以通过输入以下内容来实现:

  • source my_project_env/bin/activate

    源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$.

您的提示应更改为指示您现在在Python虚拟环境中进行操作。 您的命令提示符现在将显示如下内容: ( my_project_env ) user @ host :~/ my_project_dir $

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

至此,您已经准备好将Jupyter安装到该虚拟环境中。

步骤3 —安装Jupyter (Step 3 — Install Jupyter)

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

在您的虚拟环境处于活动状态的情况下,使用本地pip实例安装Jupyter。

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.

注意:激活虚拟环境后(当提示符之前带有(my_project_env)提示时(my_project_env) ,即使使用Python 3,也要使用pip而不是pip3 。该工具的虚拟环境副本始终命名为pip ,而与Python无关版。

  • pip install jupyter

    pip安装jupyter

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

至此,您已经成功安装了运行Jupyter所需的所有软件。 现在,我们可以启动Notebook服务器。

步骤4 —运行Jupyter Notebook (Step 4 — Run Jupyter Notebook)

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

现在,您拥有运行Jupyter Notebook所需的一切! 要运行它,执行以下命令:

  • jupyter notebook

    jupyter笔记本

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:

Jupyter Notebook的活动日志将被打印到终端上。 当您运行Jupyter Notebook时,它将在特定的端口号上运行。 您运行的第一个笔记本通常将使用端口8888 。 要检查正在运行的Jupyter Notebook的特定端口号,请参阅用于启动该端口的命令的输出:


   
   
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.

如果要在本地计算机(而不是服务器)上运行Jupyter Notebook,则可以导航到显示的URL以连接到Jupyter Notebook。 如果要在服务器上运行Jupyter Notebook,则需要使用SSH隧道连接到该服务器,如下一节所述。

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:

此时,您可以保持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

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

现在,我们将建立SSH隧道,以便我们可以访问Notebook。

第5步—使用SSH隧道连接到服务器 (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.

在本节中,我们将演示如何使用SSH隧道连接到Jupyter Notebook Web界面。 由于Jupyter Notebook将在服务器上的特定端口(例如:8888:8889等)上运行,因此SSH隧道使您能够安全地连接到服务器的端口。

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.

接下来的两个小节介绍了如何通过1)Mac或Linux或2)Windows创建SSH隧道。 请参考本地计算机的小节。

Mac或Linux的SSH隧道 (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.

如果使用的是Mac或Linux本地计算机,则创建SSH隧道的步骤与使用SSH登录到远程服务器的步骤类似,不同之处在于ssh命令中包含其他参数。 本小节将概述ssh命令成功隧道所需的其他参数。

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

可以通过在新的本地终端窗口中运行以下SSH命令来完成SSH隧道:

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

    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.

ssh命令打开SSH连接,但-L指定将本地(客户端)主机上的给定端口转发到远程(服务器)上的给定主机和端口。 这意味着服务器上第二个端口号(例如8888 )上运行的任何内容都将出现在本地计算机上的第一个端口号(例如8888 )上。

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

(可选)将端口8888更改为您选择的端口之一,以避免使用另一个进程已使用的端口。

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.

server_username是您在创建的服务器上的用户名(例如sammy ), your_server_ip是服务器的IP地址。

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

例如,对于用户名sammy和服务器地址203.0.113.0 ,命令将为:

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

    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:

如果在运行ssh -L命令后没有出现错误,则可以进入编程环境并运行Jupyter Notebook:

  • jupyter notebook

    jupyter笔记本

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.

您将收到带有URL的输出。 在本地计算机上的Web浏览器中,使用以http://localhost:8888开头的URL打开Jupyter Notebook Web界面。 确保包含令牌号,或者在http://localhost:8888提示时输入令牌号字符串。

Windows和Putty的SSH隧道 (SSH Tunneling with Windows and Putty)

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

如果您使用的是Windows,则可以使用Putty创建SSH隧道。

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

首先,输入服务器URL或IP地址作为主机名,如下所示:

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.

接下来,单击左窗格底部的SSH以展开菜单,然后单击Tunnels 。 输入要用于访问本地计算机上的Jupyter的本地端口号。 选择8000或更高版本以避免端口被其他服务使用,并将目标设置为localhost: 8888 ,其中:8888是Jupyter Notebook运行所在的端口号。

Now click the Add button, and the ports should appear in the 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.

最后,单击“ 打开”按钮以通过SSH连接到服务器并建立所需端口的通道。 在网络浏览器中导航到http://localhost: 8000 (或您选择的任何端口)以连接到服务器上运行的Jupyter Notebook。 确保包含令牌号,或者在http://localhost:8000出现提示时输入令牌号字符串。

步骤6 —使用Jupyter Notebook (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.

本节介绍使用Jupyter Notebook的基础知识。 如果您当前没有运行Jupyter Notebook,请使用jupyter notebook命令启动它。

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.

现在,您应该使用网络浏览器连接到它。 Jupyter Notebook是一个非常强大的工具,具有许多功能。 本节将概述一些基本功能,以帮助您开始使用笔记本电脑。 Jupyter Notebook将在运行它的目录中显示所有文件和文件夹,因此当您在处理项目时,请确保从项目目录中启动它。

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

要创建一个新的Notebook文件,请从右上方的下拉菜单中选择New > Python 3

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:

这将打开一个笔记本。 现在,我们可以在单元格中运行Python代码,或将单元格更改为markdown。 例如,通过单击顶部导航栏中的“ 单元格” >“ 单元格类型” >“ Markdown” ,将第一个单元格更改为接受Markdown。 现在,我们可以使用Markdown编写笔记,甚至可以通过将它们放在$$符号之间来包含用LaTeX编写的方程式。 例如,将其更改为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:

要将降价标记转换为富文本格式,请按CTRLENTER键。 您应该收到类似于以下内容的输出:

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.

您可以使用markdown单元格做笔记并记录代码。 让我们实现该方程式并打印结果。 单击顶部的单元格,然后同时按ALTENTER键以在其下方添加一个单元格。 在新单元格中输入以下代码。

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

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

要运行代码,请按CTRL+ENTER 。 您会收到以下结果:

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

现在,您可以像在其他任何Python开发环境中一样导入模块并使用Notebook!

结论 (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.

恭喜你! 您现在应该可以使用Jupyter Notebook在Markdown中编写可重现的Python代码和注释。 要从界面中快速浏览Jupyter Notebook,请从顶部导航菜单中选择“ 帮助” >“ 用户界面浏览 ”以了解更多信息。

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.

从这里开始,您可以通过阅读Python 3中的pandas和Jupyter Notebook进行数据分析和可视化,从而开始数据分析和可视化项目。

翻译自: https://www.digitalocean.com/community/tutorials/how-to-set-up-jupyter-notebook-with-python-3-on-ubuntu-20-04-and-connect-via-ssh-tunneling

 类似资料: