ZHANG BIAO . ORG

^


linux screen 命令详解

• LIUNX • 阅读: 72953

linux screen 命令详解
一、背景

系统管理员经常需要SSH 或者telent 远程登录到Linux 服务器,经常运行一些需要很长时间才能完成的任务,比如系统备份、ftp 传输等等。通常情况下我们都是为每一个这样的任务开一个远程终端窗口,因为它们执行的时间太长了。必须等待它们执行完毕,在此期间不能关掉窗口或者断开连接,否则这个任务就会被杀掉,一切半途而废了。

二、简介

GNU Screen是一款由GNU计划开发的用于命令行终端切换的自由软件。用户可以通过该软件同时连接多个本地或远程的命令行会话,并在其间自由切换。

GNU Screen可以看作是窗口管理器的命令行界面版本。它提供了统一的管理多个会话的界面和相应的功能。

会话恢复
只要Screen本身没有终止,在其内部运行的会话都可以恢复。这一点对于远程登录的用户特别有用——即使网络连接中断,用户也不会失去对已经打开的命令行会话的控制。只要再次登录到主机上执行screen -r就可以恢复会话的运行。同样在暂时离开的时候,也可以执行分离命令detach,在保证里面的程序正常运行的情况下让Screen挂起(切换到后台)。这一点和图形界面下的VNC很相似。
多窗口
在Screen环境下,所有的会话都独立的运行,并拥有各自的编号、输入、输出和窗口缓存。用户可以通过快捷键在不同的窗口下切换,并可以自由的重定向各个窗口的输入和输出。Screen实现了基本的文本操作,如复制粘贴等;还提供了类似滚动条的功能,可以查看窗口状况的历史记录。窗口还可以被分区和命名,还可以监视后台窗口的活动。
会话共享
Screen可以让一个或多个用户从不同终端多次登录一个会话,并共享会话的所有特性(比如可以看到完全相同的输出)。它同时提供了窗口访问权限的机制,可以对窗口进行密码保护。
GNU's Screen 官方站点:http://www.gnu.org/software/screen/

三、语法

screen -AmRvx -ls -wipe-h <行数>-s

参数说明

-A  将所有的视窗都调整为目前终端机的大小。
-d <作业名称>  将指定的screen作业离线。
-h <行数>  指定视窗的缓冲区行数。
-m  即使目前已在作业中的screen作业,仍强制建立新的screen作业。
-r <作业名称>  恢复离线的screen作业。
-R  先试图恢复离线的作业。若找不到离线的作业,即建立新的screen作业。
-s  指定建立新视窗时,所要执行的shell。
-S <作业名称>  指定screen作业的名称。
-v  显示版本信息。
-x  恢复之前离线的screen作业。
-ls或--list  显示目前所有的screen作业。
-wipe  检查目前所有的screen作业,并删除已经无法使用的screen作业。

四、常用screen参数

screen -S yourname -> 新建一个叫yourname的session
screen -ls -> 列出当前所有的session
screen -r yourname -> 回到yourname这个session
screen -d yourname -> 远程detach某个session
screen -d -r yourname -> 结束当前session并回到yourname这个session

在每个screen session 下,所有命令都以 ctrl+a(C-a) 开始。
C-a ? -> 显示所有键绑定信息
C-a c -> 创建一个新的运行shell的窗口并切换到该窗口
C-a n -> Next,切换到下一个 window
C-a p -> Previous,切换到前一个 window
C-a 0..9 -> 切换到第 0..9 个 window
Ctrl+a [Space] -> 由视窗0循序切换到视窗9
C-a C-a -> 在两个最近使用的 window 间切换
C-a x -> 锁住当前的 window,需用用户密码解锁
C-a d -> detach,暂时离开当前session,将目前的 screen session (可能含有多个 windows) 丢到后台执行,并会回到还没进 screen 时的状态,此时在 screen session 里,每个 window 内运行的 process (无论是前台/后台)都在继续执行,即使 logout 也不影响。
C-a z -> 把当前session放到后台执行,用 shell 的 fg 命令则可回去。
C-a w -> 显示所有窗口列表
C-a t -> Time,显示当前时间,和系统的 load
C-a k -> kill window,强行关闭当前的 window
C-a [ -> 进入 copy mode,在 copy mode 下可以回滚、搜索、复制就像用使用 vi 一样

C-b Backward,PageUp 
C-f Forward,PageDown 
H(大写) High,将光标移至左上角 
L Low,将光标移至左下角 
0 移到行首 
$ 行末 
w forward one word,以字为单位往前移 
b backward one word,以字为单位往后移 
Space 第一次按为标记区起点,第二次按为终点 
Esc 结束 copy mode 

C-a ] -> Paste,把刚刚在 copy mode 选定的内容贴上

文章标签: liunx
点此生成 >> 文章海报


已经是第一篇文章了~
下一篇 : 2021年双十二,博客搭建完成
留言

取消回复



已有 28310 条留言
  1. 2026-06-14 16:06:47
    回复

    A piece that was confident enough to leave some questions open rather than forcing closure, and a look at frostcoast continued that intellectual honesty, content that admits the limits of its scope is more trustworthy than content that pretends to total understanding and this site has the right calibration on certainty consistently.

  2. 2026-06-14 16:06:25
    回复

    Coming back tomorrow when I can give this a proper read, the post deserves better attention than I can give right now, and a look at woodharborvendorparlor suggests there is plenty more here that deserves the same treatment, definitely a site I will be exploring properly over the next few days when I can.

  3. 2026-06-14 16:06:47
    回复

    Now placing this in the same category as a few other sites I have come to trust, and a look at glassharborcraftcollective continued the placement decision, the small category of fully trusted sites is one I extend rarely and only after multiple positive reading sessions and this site has earned the category placement methodically over time.

  4. 2026-06-14 16:06:18
    回复

    Honestly this was a good read, no jargon and no padding, and a short look at calmcoveartisanexchange kept that same feel going which I really appreciated, the writer clearly knows the topic well enough to explain it without hiding behind big words or filler that often gets used to seem clever.

  5. 2026-06-14 16:06:03
    回复

    Bookmark folder created specifically for this site, and a look at canyonbrookmarketfoundry confirmed the dedicated folder was the right call, dedicated folders for individual sites are a level of organisation I rarely deploy and this site has earned that level of dedicated tracking based on the consistency I have seen so far across sessions.

  6. 2026-06-14 16:06:41
    回复

    Ребята, выручайте! Кот старый диван в клочья разодрал, надо перетягивать. Ищу, где можно ткань для обивки мебели купить не по космическим ценам. обивочная ткань для мебели цена обивочная ткань для мебели цена Интересно про ткань для обивки мебели — какой вариант самый практичный для дивана, где постоянно лежат с чипсами. Буду благодарен за любые советы, особенно от тех, кто сам перетягивал.

  7. 2026-06-14 16:06:06
    回复

    Reading this fit naturally into my afternoon walk because I was reading on my phone, and a stop at goodsrisestore continued well in that walking format, content that survives mobile reading without becoming awkward is content with format flexibility and this site has clearly thought about how it reads across different devices today.

  8. 2026-06-14 16:06:31
    回复

    Felt like I was reading something written by someone who actually thinks about the topic rather than reciting it, and a look at gemcoasts reinforced that impression, the difference between recited content and considered content is huge and this site clearly belongs to the latter category which I appreciate as a careful reader looking for substance.

  9. 2026-06-14 16:06:12
    回复

    Let me save you some serious time, learned this the hard way. Then you actually show up to the local office to pick up the car. Different vehicle parked outside, curb rash on every rim, and that "all-inclusive rate"? Ha, doesn't include the mandatory $300 cleaning fee or the $25 per day toll pass you can't decline. Living here six years and still almost fall for this stuff sometimes. When you genuinely need a legit and reliable premium ride to cruise around, stay far away from the airport rental center. Miami without proper wheels is basically a nightmare, whether you are doing South Beach dinner plans, Sunny Isles sunrise cruise, or a quick run down to the Florida Keys.

    Most of these local agencies are just polished garbage with decent Google reviews bought somewhere, but I eventually found a service where what you reserve is exactly what rolls up, no surprises. If you are looking for the only trustworthy source for premium vehicles across South Florida, check the current details here: exotic car rental coral gables https://luxury-car-rental-miami-6.com. Also, definitely bring serious shades unless you enjoy driving straight into the sun every single evening. Anyway, glad there's at least one honest operator left in this rental jungle, hope this helps some of you save a few bucks.

  10. 2026-06-14 16:06:05
    回复

    Вот такая беда приключилась — близкий ломается, а что делать — совсем не знаешь . Моя семья такое пережила недавно. Думаешь, сам справится, но хрен там. Нужна реальная помощь . Обзвонил десяток контор — одни обещания . Пока не нашел один действительно рабочий вариант. Нужна срочно анонимное лечение алкоголиков — не ведись на дешевые акции . У нас в Воронеже, если честно, хватает левых контор без лицензии. Вся проверенная информация ниже по ссылке: наркологическая помощь в воронеже https://narkologicheskaya-pomoshh-voronezh-12.ru Откровенно говоря, после того как ознакомился, многое прояснилось . И про кодирование, и про реабилитацию . И цены адекватные. Рекомендую не тянуть .

  11. 2026-06-14 16:06:40
    回复

    Worth saying that this is one of the better things I have read on the topic in months, and a stop at echobrookvendorfoundry reinforced that ranking, the topic is well covered by many sources but few do it with this level of care and the few that do deserve to be flagged so other readers can find them.

  12. 2026-06-14 16:06:18
    回复

    Now recognising the editorial wisdom of letting some questions remain open at the end, and a look at woodharborcommercegallery continued that intellectual honesty, content that does not force closure on contested questions is content that respects the limits of knowledge and this site has clearly developed the maturity to know when to leave space.

  13. 2026-06-14 16:06:48
    回复

    Worth your time, that is the simplest endorsement I can give, and a stop at discovernewfocus extends that endorsement across the rest of the site, this is one of those increasingly rare places that delivers on what it promises rather than over selling the content and under delivering on substance every time which I find frustrating elsewhere.

  14. 2026-06-14 17:06:46
    回复

    Felt the writer was being honest with the reader which is rare enough that I want to acknowledge it, and a look at pineharbortradehall continued that honest feel, content built on actual knowledge rather than aggregated summaries is something I value highly and rarely come across in regular searches on the open internet these days.

  15. 2026-06-14 17:06:51
    回复

    I've got the scars to prove it, the rental landscape down here is crazy. You find this amazing deal online: brand new Beamer, unlimited miles, price that makes you smile. Plus they freeze a surprise $2500 on your card for a week right before giving you the keys. Fool me eight times? That's just another Tuesday in the 305, lesson learned. If you are trying to find a legitimate luxury fleet without getting ripped off, run far from the airport counters. Anyone who's waited for an Uber in August understands exactly what I mean about this city, especially since the AC must be arctic cold and unlimited miles non-negotiable.

    I've run through maybe 45 rental companies across Dade, Broward, and Monroe, but I eventually found a service where what you book is exactly what shows up, no surprises, no fine print nightmares. If you are looking for the only honest source for premium wheels across South Florida, check the current details here: benz for rent https://luxury-car-rental-miami-8.com. Also, definitely bring serious shades unless you enjoy driving straight into the sun like a zombie every single evening. Just drive safe out there and absolutely skip that "windshield protection" upsell — pure profit for them, zero value for you. hope this helps some of you save a few bucks.

  16. 2026-06-14 17:06:10
    回复

    Started reading expecting to disagree and ended mostly nodding along, and a look at futuregoodszone continued the pattern, content that wins agreement through evidence and reasoning rather than rhetorical force is the kind that actually shifts minds and this site clearly knows how to do that across what I have read so far.

  17. 2026-06-14 17:06:40
    回复

    Worth pointing out that the writer made the topic feel more interesting than I had been expecting, and a look at alpinecovemarkethall continued that elevation effect, content that improves the apparent quality of its subject through skilled treatment is doing something real and this site has clearly developed that kind of editorial alchemy throughout.

  18. 2026-06-14 17:06:03
    回复

    More original than the recycled takes I keep finding on the topic elsewhere, and a quick look at ivoryharborvendorparlor confirmed it, the kind of site that has its own voice rather than echoing whatever is trending which makes it stand out as a refreshing change from the usual rotation of generic content I see daily.

  19. 2026-06-14 17:06:05
    回复

    Вот такая беда приключилась — родственник подсел , а куда бежать — просто руки опускаются. Моя семья такое пережила недавно. Сначала кажется, что обойдется , но хрен там. Нужна профессиональная помощь . Обзвонил десяток контор — сплошной развод . Пока не нашел один нормальный вариант. Если ищешь где получить круглосуточная наркологическая служба — не ведись на дешевые акции . В Воронеже , кстати , хватает левых контор без лицензии. Реальные контакты ниже по ссылке: анонимное лечение алкоголизма анонимное лечение алкоголизма Честно скажу , после того как прочитал , понял свои ошибки. И про кодирование, и про условия в клинике. И цены адекватные. Рекомендую не тянуть .

  20. 2026-06-14 17:06:27
    回复

    Thanks for taking the time to write this, it is clear that some thought went into how each point would land, and after I went through walnutcoveartisanexchange I had a better grip on the topic, real value without the usual marketing noise people have to put up with online when searching for answers.